UNPKG

1.77 kBJavaScriptView Raw
1import _checkForMethod from "./internal/_checkForMethod.js";
2import _curry2 from "./internal/_curry2.js";
3import reduceBy from "./reduceBy.js";
4/**
5 * Splits a list into sub-lists stored in an object, based on the result of
6 * calling a String-returning function on each element, and grouping the
7 * results according to values returned.
8 *
9 * Dispatches to the `groupBy` method of the second argument, if present.
10 *
11 * Acts as a transducer if a transformer is given in list position.
12 *
13 * @func
14 * @memberOf R
15 * @since v0.1.0
16 * @category List
17 * @sig (a -> String) -> [a] -> {String: [a]}
18 * @param {Function} fn Function :: a -> String
19 * @param {Array} list The array to group
20 * @return {Object} An object with the output of `fn` for keys, mapped to arrays of elements
21 * that produced that key when passed to `fn`.
22 * @see R.reduceBy, R.transduce
23 * @example
24 *
25 * const byGrade = R.groupBy(function(student) {
26 * const score = student.score;
27 * return score < 65 ? 'F' :
28 * score < 70 ? 'D' :
29 * score < 80 ? 'C' :
30 * score < 90 ? 'B' : 'A';
31 * });
32 * const students = [{name: 'Abby', score: 84},
33 * {name: 'Eddy', score: 58},
34 * // ...
35 * {name: 'Jack', score: 69}];
36 * byGrade(students);
37 * // {
38 * // 'A': [{name: 'Dianne', score: 99}],
39 * // 'B': [{name: 'Abby', score: 84}]
40 * // // ...,
41 * // 'F': [{name: 'Eddy', score: 58}]
42 * // }
43 */
44
45var groupBy =
46/*#__PURE__*/
47_curry2(
48/*#__PURE__*/
49_checkForMethod('groupBy',
50/*#__PURE__*/
51reduceBy(function (acc, item) {
52 if (acc == null) {
53 acc = [];
54 }
55
56 acc.push(item);
57 return acc;
58}, null)));
59
60export default groupBy;
\No newline at end of file