addIndexRight.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import _concat from "./internal/_concat.js";
  2. import _curry1 from "./internal/_curry1.js";
  3. import curryN from "./curryN.js";
  4. /**
  5. * As with `addIndex`, `addIndexRight` creates a new list iteration function
  6. * from an existing one by adding two new parameters to its callback function:
  7. * the current index, and the entire list.
  8. *
  9. * Unlike `addIndex`, `addIndexRight` iterates from the right to the left.
  10. *
  11. * @func
  12. * @memberOf R
  13. * @since v0.29.0
  14. * @category Function
  15. * @category List
  16. * @sig ((a ... -> b) ... -> [a] -> *) -> (a ..., Int, [a] -> b) ... -> [a] -> *)
  17. * @param {Function} fn A list iteration function that does not pass index or list to its callback
  18. * @return {Function} An altered list iteration function that passes (item, index, list) to its callback
  19. * @example
  20. *
  21. * const revmap = (fn, ary) => R.map(fn, R.reverse(ary));
  22. * const revmapIndexed = R.addIndexRight(revmap);
  23. * revmapIndexed((val, idx) => idx + '-' + val, ['f', 'o', 'o', 'b', 'a', 'r']);
  24. * //=> [ '5-r', '4-a', '3-b', '2-o', '1-o', '0-f' ]
  25. */
  26. var addIndexRight =
  27. /*#__PURE__*/
  28. _curry1(function addIndex(fn) {
  29. return curryN(fn.length, function () {
  30. var origFn = arguments[0];
  31. var list = arguments[arguments.length - 1];
  32. var idx = list.length - 1;
  33. var args = Array.prototype.slice.call(arguments, 0);
  34. args[0] = function () {
  35. var result = origFn.apply(this, _concat(arguments, [idx, list]));
  36. idx -= 1;
  37. return result;
  38. };
  39. return fn.apply(this, args);
  40. });
  41. });
  42. export default addIndexRight;