You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.7 KiB

4 years ago
  1. import _checkForMethod from "./internal/_checkForMethod.js";
  2. import _curry2 from "./internal/_curry2.js";
  3. import 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. var groupBy =
  45. /*#__PURE__*/
  46. _curry2(
  47. /*#__PURE__*/
  48. _checkForMethod('groupBy',
  49. /*#__PURE__*/
  50. reduceBy(function (acc, item) {
  51. if (acc == null) {
  52. acc = [];
  53. }
  54. acc.push(item);
  55. return acc;
  56. }, null)));
  57. export default groupBy;