Add transform

This commit is contained in:
Angelos Chalaris
2018-01-12 13:55:49 +02:00
parent b660101f80
commit c1c37f8191
2 changed files with 18 additions and 0 deletions

17
snippets/transform.md Normal file
View File

@ -0,0 +1,17 @@
### transform
Applies a function against an accumulator and each key in the object (from left to right).
Use `Object.keys(obj)` to iterate over each key in the object, `Array.reduce()` to call the apply the specified function against the given accumulator.
```js
const transform = (obj, fn, acc) =>
Object.keys(obj).reduce((a, k) => fn(a, obj[k], k, obj), acc);
```
```js
transform({ 'a': 1, 'b': 2, 'c': 1 }, (r, v, k) => {
(r[v] || (r[v] = [])).push(k);
return r;
}, {}); // { '1': ['a', 'c'], '2': ['b'] }
```