1 | /** @module collections */
|
2 | const { curry } = require('../fp');
|
3 |
|
4 | /** Reduces an array/object based on the reduction function
|
5 | * and the initialization value passed
|
6 | * @argument {function} fn Reduce function
|
7 | * @argument {*} init Initial value to accumulate
|
8 | * @argument {Array|Object} collection iterable collection to traverse
|
9 | * @example
|
10 | * //Arrays
|
11 | * reduce((a,b)=> a+b,0,[1,2,3]) // -> 6
|
12 | * reduce((a,b)=> a.concat(b+1),[],[1,2,3]) // -> [2,3,4]
|
13 | * //Objects
|
14 | * reduce((a,v,k)=> ({..a,[k],v+1}),{},{a:1,b:2}) // -> {a:2,b:3}
|
15 | * @returns {*}
|
16 | * @see [collectionsTest.js](https://github.com/nerac/keyu/blob/master/test/collectionsTest.js)
|
17 | * @method
|
18 | * */
|
19 | const reduce = curry((fn, init, collection) => {
|
20 | if (Array.isArray(collection)) {
|
21 | return collection.reduce(fn, init);
|
22 | }
|
23 | return Object.entries(collection).reduce((acc, [k, v]) => fn(acc, v, k), init);
|
24 | });
|
25 |
|
26 | /** Maps over an array/object applying the passed function
|
27 | * @argument {function} fn Reduce function
|
28 | * @argument {Array|Object} collection iterable collection to traverse
|
29 | * @example
|
30 | * //Arrays
|
31 | * map(x => x+1, [1,2,3]) // -> [2,3,4]
|
32 | * //Objects
|
33 | * map(x => x+1, {a:1,b:2}) // -> {a:2,b:3}
|
34 | * @returns {Array|Object}
|
35 | * @see [collectionsTest.js](https://github.com/nerac/keyu/blob/master/test/collectionsTest.js)
|
36 | * @method
|
37 | * */
|
38 | const map = curry((fn, collection) => {
|
39 | if (Array.isArray(collection)) {
|
40 | return collection.map(fn);
|
41 | }
|
42 | return reduce((acc, v, k) => ({ ...acc, [k]: fn(v, k) }), {}, collection);
|
43 | });
|
44 |
|
45 | /** Filters an array/object based on the boolean evaluation of the passed function.
|
46 | * @argument {function} fn Reduce function
|
47 | * @argument {Array|Object} collection iterable collection to traverse
|
48 | * @example
|
49 | * //Arrays
|
50 | * filter(x => x > 1, [1,2,3]) // -> [2,3]
|
51 | * //Objects
|
52 | * filter(x => x > 1, {a:1,b:2}) // -> {b:2}
|
53 | * @returns {Array|Object}
|
54 | * @see [collectionsTest.js](https://github.com/nerac/keyu/blob/master/test/collectionsTest.js)
|
55 | * @method
|
56 | * */
|
57 | const filter = curry((fn, collection) => {
|
58 | if (Array.isArray(collection)) {
|
59 | return collection.filter(fn);
|
60 | }
|
61 | return reduce((acc, v, k) => (fn(v, k) && { ...acc, [k]: v }) || {}, {}, collection);
|
62 | });
|
63 |
|
64 | module.exports = { map, filter, reduce };
|