source: node_modules/ramda/es/reduceBy.js

main
Last change on this file was d24f17c, checked in by Aleksandar Panovski <apano77@…>, 15 months ago

Initial commit

  • Property mode set to 100644
File size: 2.6 KB
RevLine 
[d24f17c]1import _clone from "./internal/_clone.js";
2import _curryN from "./internal/_curryN.js";
3import _dispatchable from "./internal/_dispatchable.js";
4import _has from "./internal/_has.js";
5import _reduced from "./internal/_reduced.js";
6import _xReduce from "./internal/_xReduce.js";
7import _xreduceBy from "./internal/_xreduceBy.js";
8import _xwrap from "./internal/_xwrap.js";
9/**
10 * Groups the elements of the list according to the result of calling
11 * the String-returning function `keyFn` on each element and reduces the elements
12 * of each group to a single value via the reducer function `valueFn`.
13 *
14 * The value function receives two values: *(acc, value)*. It may use
15 * [`R.reduced`](#reduced) to short circuit the iteration.
16 *
17 * This function is basically a more general [`groupBy`](#groupBy) function.
18 *
19 * Acts as a transducer if a transformer is given in list position.
20 *
21 * @func
22 * @memberOf R
23 * @since v0.20.0
24 * @category List
25 * @sig ((a, b) -> a) -> a -> (b -> String) -> [b] -> {String: a}
26 * @param {Function} valueFn The function that reduces the elements of each group to a single
27 * value. Receives two values, accumulator for a particular group and the current element.
28 * @param {*} acc The (initial) accumulator value for each group.
29 * @param {Function} keyFn The function that maps the list's element into a key.
30 * @param {Array} list The array to group.
31 * @return {Object} An object with the output of `keyFn` for keys, mapped to the output of
32 * `valueFn` for elements which produced that key when passed to `keyFn`.
33 * @see R.groupBy, R.reduce, R.reduced
34 * @example
35 *
36 * const groupNames = (acc, {name}) => acc.concat(name)
37 * const toGrade = ({score}) =>
38 * score < 65 ? 'F' :
39 * score < 70 ? 'D' :
40 * score < 80 ? 'C' :
41 * score < 90 ? 'B' : 'A'
42 *
43 * var students = [
44 * {name: 'Abby', score: 83},
45 * {name: 'Bart', score: 62},
46 * {name: 'Curt', score: 88},
47 * {name: 'Dora', score: 92},
48 * ]
49 *
50 * reduceBy(groupNames, [], toGrade, students)
51 * //=> {"A": ["Dora"], "B": ["Abby", "Curt"], "F": ["Bart"]}
52 */
53
54var reduceBy =
55/*#__PURE__*/
56_curryN(4, [],
57/*#__PURE__*/
58_dispatchable([], _xreduceBy, function reduceBy(valueFn, valueAcc, keyFn, list) {
59 var xf = _xwrap(function (acc, elt) {
60 var key = keyFn(elt);
61 var value = valueFn(_has(key, acc) ? acc[key] : _clone(valueAcc, false), elt);
62
63 if (value && value['@@transducer/reduced']) {
64 return _reduced(acc);
65 }
66
67 acc[key] = value;
68 return acc;
69 });
70
71 return _xReduce(xf, {}, list);
72}));
73
74export default reduceBy;
Note: See TracBrowser for help on using the repository browser.