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.

47 lines
1.6 KiB

4 years ago
  1. import _concat from "./internal/_concat.js";
  2. import _curry1 from "./internal/_curry1.js";
  3. import curryN from "./curryN.js";
  4. /**
  5. * Creates a new list iteration function from an existing one by adding two new
  6. * parameters to its callback function: the current index, and the entire list.
  7. *
  8. * This would turn, for instance, [`R.map`](#map) function into one that
  9. * more closely resembles `Array.prototype.map`. Note that this will only work
  10. * for functions in which the iteration callback function is the first
  11. * parameter, and where the list is the last parameter. (This latter might be
  12. * unimportant if the list parameter is not used.)
  13. *
  14. * @func
  15. * @memberOf R
  16. * @since v0.15.0
  17. * @category Function
  18. * @category List
  19. * @sig ((a ... -> b) ... -> [a] -> *) -> ((a ..., Int, [a] -> b) ... -> [a] -> *)
  20. * @param {Function} fn A list iteration function that does not pass index or list to its callback
  21. * @return {Function} An altered list iteration function that passes (item, index, list) to its callback
  22. * @example
  23. *
  24. * const mapIndexed = R.addIndex(R.map);
  25. * mapIndexed((val, idx) => idx + '-' + val, ['f', 'o', 'o', 'b', 'a', 'r']);
  26. * //=> ['0-f', '1-o', '2-o', '3-b', '4-a', '5-r']
  27. */
  28. var addIndex =
  29. /*#__PURE__*/
  30. _curry1(function addIndex(fn) {
  31. return curryN(fn.length, function () {
  32. var idx = 0;
  33. var origFn = arguments[0];
  34. var list = arguments[arguments.length - 1];
  35. var args = Array.prototype.slice.call(arguments, 0);
  36. args[0] = function () {
  37. var result = origFn.apply(this, _concat(arguments, [idx, list]));
  38. idx += 1;
  39. return result;
  40. };
  41. return fn.apply(this, args);
  42. });
  43. });
  44. export default addIndex;