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.

53 lines
1.5 KiB

4 years ago
  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. * R.groupWith(R.eqBy(isVowel), 'aestiou')
  30. * //=> ['ae', 'st', 'iou']
  31. */
  32. var groupWith =
  33. /*#__PURE__*/
  34. _curry2(function (fn, list) {
  35. var res = [];
  36. var idx = 0;
  37. var len = list.length;
  38. while (idx < len) {
  39. var nextidx = idx + 1;
  40. while (nextidx < len && fn(list[nextidx - 1], list[nextidx])) {
  41. nextidx += 1;
  42. }
  43. res.push(list.slice(idx, nextidx));
  44. idx = nextidx;
  45. }
  46. return res;
  47. });
  48. export default groupWith;