UNPKG

2.37 kBJavaScriptView Raw
1var _clone =
2/*#__PURE__*/
3require("./internal/_clone");
4
5var _curryN =
6/*#__PURE__*/
7require("./internal/_curryN");
8
9var _dispatchable =
10/*#__PURE__*/
11require("./internal/_dispatchable");
12
13var _has =
14/*#__PURE__*/
15require("./internal/_has");
16
17var _reduce =
18/*#__PURE__*/
19require("./internal/_reduce");
20
21var _xreduceBy =
22/*#__PURE__*/
23require("./internal/_xreduceBy");
24/**
25 * Groups the elements of the list according to the result of calling
26 * the String-returning function `keyFn` on each element and reduces the elements
27 * of each group to a single value via the reducer function `valueFn`.
28 *
29 * This function is basically a more general [`groupBy`](#groupBy) function.
30 *
31 * Acts as a transducer if a transformer is given in list position.
32 *
33 * @func
34 * @memberOf R
35 * @since v0.20.0
36 * @category List
37 * @sig ((a, b) -> a) -> a -> (b -> String) -> [b] -> {String: a}
38 * @param {Function} valueFn The function that reduces the elements of each group to a single
39 * value. Receives two values, accumulator for a particular group and the current element.
40 * @param {*} acc The (initial) accumulator value for each group.
41 * @param {Function} keyFn The function that maps the list's element into a key.
42 * @param {Array} list The array to group.
43 * @return {Object} An object with the output of `keyFn` for keys, mapped to the output of
44 * `valueFn` for elements which produced that key when passed to `keyFn`.
45 * @see R.groupBy, R.reduce
46 * @example
47 *
48 * const groupNames = (acc, {name}) => acc.concat(name)
49 * const toGrade = ({score}) =>
50 * score < 65 ? 'F' :
51 * score < 70 ? 'D' :
52 * score < 80 ? 'C' :
53 * score < 90 ? 'B' : 'A'
54 *
55 * var students = [
56 * {name: 'Abby', score: 83},
57 * {name: 'Bart', score: 62},
58 * {name: 'Curt', score: 88},
59 * {name: 'Dora', score: 92},
60 * ]
61 *
62 * reduceBy(groupNames, [], toGrade, students)
63 * //=> {"A": ["Dora"], "B": ["Abby", "Curt"], "F": ["Bart"]}
64 */
65
66
67var reduceBy =
68/*#__PURE__*/
69_curryN(4, [],
70/*#__PURE__*/
71_dispatchable([], _xreduceBy, function reduceBy(valueFn, valueAcc, keyFn, list) {
72 return _reduce(function (acc, elt) {
73 var key = keyFn(elt);
74 acc[key] = valueFn(_has(key, acc) ? acc[key] : _clone(valueAcc, [], [], false), elt);
75 return acc;
76 }, {}, list);
77}));
78
79module.exports = reduceBy;
\No newline at end of file