reduceRight.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import _curry3 from "./internal/_curry3.js";
  2. /**
  3. * Returns a single item by iterating through the list, successively calling
  4. * the iterator function and passing it an accumulator value and the current
  5. * value from the array, and then passing the result to the next call.
  6. *
  7. * Similar to [`reduce`](#reduce), except moves through the input list from the
  8. * right to the left.
  9. *
  10. * The iterator function receives two values: *(value, acc)*, while the arguments'
  11. * order of `reduce`'s iterator function is *(acc, value)*. `reduceRight` may use [`reduced`](#reduced)
  12. * to short circuit the iteration.
  13. *
  14. * Note: `R.reduceRight` does not skip deleted or unassigned indices (sparse
  15. * arrays), unlike the native `Array.prototype.reduceRight` method. For more details
  16. * on this behavior, see:
  17. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight#Description
  18. *
  19. * Be cautious of mutating and returning the accumulator. If you reuse it across
  20. * invocations, it will continue to accumulate onto the same value. The general
  21. * recommendation is to always return a new value. If you can't do so for
  22. * performance reasons, then be sure to reinitialize the accumulator on each
  23. * invocation.
  24. *
  25. * @func
  26. * @memberOf R
  27. * @since v0.1.0
  28. * @category List
  29. * @sig ((a, b) -> b) -> b -> [a] -> b
  30. * @param {Function} fn The iterator function. Receives two values, the current element from the array
  31. * and the accumulator.
  32. * @param {*} acc The accumulator value.
  33. * @param {Array} list The list to iterate over.
  34. * @return {*} The final, accumulated value.
  35. * @see R.reduce, R.addIndex, R.reduced
  36. * @example
  37. *
  38. * R.reduceRight(R.subtract, 0, [1, 2, 3, 4]) // => (1 - (2 - (3 - (4 - 0)))) = -2
  39. * // - -2
  40. * // / \ / \
  41. * // 1 - 1 3
  42. * // / \ / \
  43. * // 2 - ==> 2 -1
  44. * // / \ / \
  45. * // 3 - 3 4
  46. * // / \ / \
  47. * // 4 0 4 0
  48. *
  49. * @symb R.reduceRight(f, a, [b, c, d]) = f(b, f(c, f(d, a)))
  50. */
  51. var reduceRight =
  52. /*#__PURE__*/
  53. _curry3(function reduceRight(fn, acc, list) {
  54. var idx = list.length - 1;
  55. while (idx >= 0) {
  56. acc = fn(list[idx], acc);
  57. if (acc && acc['@@transducer/reduced']) {
  58. acc = acc['@@transducer/value'];
  59. break;
  60. }
  61. idx -= 1;
  62. }
  63. return acc;
  64. });
  65. export default reduceRight;