collectBy.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import _curry2 from "./internal/_curry2.js";
  2. import _reduce from "./internal/_reduce.js";
  3. /**
  4. * Splits a list into sub-lists, based on the result of calling a key-returning function on each element,
  5. * and grouping the results according to values returned.
  6. *
  7. * @func
  8. * @memberOf R
  9. * @since v0.28.0
  10. * @category List
  11. * @typedefn Idx = String | Int | Symbol
  12. * @sig Idx a => (b -> a) -> [b] -> [[b]]
  13. * @param {Function} fn Function :: a -> Idx
  14. * @param {Array} list The array to group
  15. * @return {Array}
  16. * An array of arrays where each sub-array contains items for which
  17. * the String-returning function has returned the same value.
  18. * @see R.groupBy, R.partition
  19. * @example
  20. * R.collectBy(R.prop('type'), [
  21. * {type: 'breakfast', item: '☕️'},
  22. * {type: 'lunch', item: '🌯'},
  23. * {type: 'dinner', item: '🍝'},
  24. * {type: 'breakfast', item: '🥐'},
  25. * {type: 'lunch', item: '🍕'}
  26. * ]);
  27. *
  28. * // [ [ {type: 'breakfast', item: '☕️'},
  29. * // {type: 'breakfast', item: '🥐'} ],
  30. * // [ {type: 'lunch', item: '🌯'},
  31. * // {type: 'lunch', item: '🍕'} ],
  32. * // [ {type: 'dinner', item: '🍝'} ] ]
  33. */
  34. var collectBy =
  35. /*#__PURE__*/
  36. _curry2(function collectBy(fn, list) {
  37. var group = _reduce(function (o, x) {
  38. var tag = fn(x);
  39. if (o[tag] === undefined) {
  40. o[tag] = [];
  41. }
  42. o[tag].push(x);
  43. return o;
  44. }, {}, list);
  45. var newList = [];
  46. for (var tag in group) {
  47. newList.push(group[tag]);
  48. }
  49. return newList;
  50. });
  51. export default collectBy;