transduce.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import _xReduce from "./internal/_xReduce.js";
  2. import _xwrap from "./internal/_xwrap.js";
  3. import curryN from "./curryN.js";
  4. /**
  5. * Initializes a transducer using supplied iterator function. Returns a single
  6. * item by iterating through the list, successively calling the transformed
  7. * iterator function and passing it an accumulator value and the current value
  8. * from the array, and then passing the result to the next call.
  9. *
  10. * The iterator function receives two values: *(acc, value)*. It will be
  11. * wrapped as a transformer to initialize the transducer. A transformer can be
  12. * passed directly in place of an iterator function. In both cases, iteration
  13. * may be stopped early with the [`R.reduced`](#reduced) function.
  14. *
  15. * A transducer is a function that accepts a transformer and returns a
  16. * transformer and can be composed directly.
  17. *
  18. * A transformer is an object that provides a 2-arity reducing iterator
  19. * function, step, 0-arity initial value function, init, and 1-arity result
  20. * extraction function, result. The step function is used as the iterator
  21. * function in reduce. The result function is used to convert the final
  22. * accumulator into the return type and in most cases is
  23. * [`R.identity`](#identity). The init function can be used to provide an
  24. * initial accumulator, but is ignored by transduce.
  25. *
  26. * The iteration is performed with [`R.reduce`](#reduce) after initializing the transducer.
  27. *
  28. * @func
  29. * @memberOf R
  30. * @since v0.12.0
  31. * @category List
  32. * @sig (c -> c) -> ((a, b) -> a) -> a -> [b] -> a
  33. * @param {Function} xf The transducer function. Receives a transformer and returns a transformer.
  34. * @param {Function} fn The iterator function. Receives two values, the accumulator and the
  35. * current element from the array. Wrapped as transformer, if necessary, and used to
  36. * initialize the transducer
  37. * @param {*} acc The initial accumulator value.
  38. * @param {Array} list The list to iterate over.
  39. * @return {*} The final, accumulated value.
  40. * @see R.reduce, R.reduced, R.into
  41. * @example
  42. *
  43. * const numbers = [1, 2, 3, 4];
  44. * const transducer = R.compose(R.map(R.add(1)), R.take(2));
  45. * R.transduce(transducer, R.flip(R.append), [], numbers); //=> [2, 3]
  46. *
  47. * const isOdd = (x) => x % 2 !== 0;
  48. * const firstOddTransducer = R.compose(R.filter(isOdd), R.take(1));
  49. * R.transduce(firstOddTransducer, R.flip(R.append), [], R.range(0, 100)); //=> [1]
  50. */
  51. var transduce =
  52. /*#__PURE__*/
  53. curryN(4, function transduce(xf, fn, acc, list) {
  54. return _xReduce(xf(typeof fn === 'function' ? _xwrap(fn) : fn), acc, list);
  55. });
  56. export default transduce;