groupWith.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import _curry2 from "./internal/_curry2.js";
  2. /**
  3. * Takes a list and returns a list of lists where each sublist's elements are
  4. * all satisfied pairwise comparison according to the provided function.
  5. * Only adjacent elements are passed to the comparison function.
  6. *
  7. * @func
  8. * @memberOf R
  9. * @since v0.21.0
  10. * @category List
  11. * @sig ((a, a) → Boolean) → [a] → [[a]]
  12. * @param {Function} fn Function for determining whether two given (adjacent)
  13. * elements should be in the same group
  14. * @param {Array} list The array to group. Also accepts a string, which will be
  15. * treated as a list of characters.
  16. * @return {List} A list that contains sublists of elements,
  17. * whose concatenations are equal to the original list.
  18. * @example
  19. *
  20. * R.groupWith(R.equals, [0, 1, 1, 2, 3, 5, 8, 13, 21])
  21. * //=> [[0], [1, 1], [2], [3], [5], [8], [13], [21]]
  22. *
  23. * R.groupWith((a, b) => a + 1 === b, [0, 1, 1, 2, 3, 5, 8, 13, 21])
  24. * //=> [[0, 1], [1, 2, 3], [5], [8], [13], [21]]
  25. *
  26. * R.groupWith((a, b) => a % 2 === b % 2, [0, 1, 1, 2, 3, 5, 8, 13, 21])
  27. * //=> [[0], [1, 1], [2], [3, 5], [8], [13, 21]]
  28. *
  29. * const isVowel = R.test(/^[aeiou]$/i);
  30. * R.groupWith(R.eqBy(isVowel), 'aestiou')
  31. * //=> ['ae', 'st', 'iou']
  32. */
  33. var groupWith =
  34. /*#__PURE__*/
  35. _curry2(function (fn, list) {
  36. var res = [];
  37. var idx = 0;
  38. var len = list.length;
  39. while (idx < len) {
  40. var nextidx = idx + 1;
  41. while (nextidx < len && fn(list[nextidx - 1], list[nextidx])) {
  42. nextidx += 1;
  43. }
  44. res.push(list.slice(idx, nextidx));
  45. idx = nextidx;
  46. }
  47. return res;
  48. });
  49. export default groupWith;