converge.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import _curry2 from "./internal/_curry2.js";
  2. import _map from "./internal/_map.js";
  3. import curryN from "./curryN.js";
  4. import max from "./max.js";
  5. import pluck from "./pluck.js";
  6. import reduce from "./reduce.js";
  7. /**
  8. * Accepts a converging function and a list of branching functions and returns
  9. * a new function. The arity of the new function is the same as the arity of
  10. * the longest branching function. When invoked, this new function is applied
  11. * to some arguments, and each branching function is applied to those same
  12. * arguments. The results of each branching function are passed as arguments
  13. * to the converging function to produce the return value.
  14. *
  15. * @func
  16. * @memberOf R
  17. * @since v0.4.2
  18. * @category Function
  19. * @sig ((x1, x2, ...) -> z) -> [((a, b, ...) -> x1), ((a, b, ...) -> x2), ...] -> (a -> b -> ... -> z)
  20. * @param {Function} after A function. `after` will be invoked with the return values of
  21. * `fn1` and `fn2` as its arguments.
  22. * @param {Array} functions A list of functions.
  23. * @return {Function} A new function.
  24. * @see R.useWith
  25. * @example
  26. *
  27. * const average = R.converge(R.divide, [R.sum, R.length])
  28. * average([1, 2, 3, 4, 5, 6, 7]) //=> 4
  29. *
  30. * const strangeConcat = R.converge(R.concat, [R.toUpper, R.toLower])
  31. * strangeConcat("Yodel") //=> "YODELyodel"
  32. *
  33. * @symb R.converge(f, [g, h])(a, b) = f(g(a, b), h(a, b))
  34. */
  35. var converge =
  36. /*#__PURE__*/
  37. _curry2(function converge(after, fns) {
  38. return curryN(reduce(max, 0, pluck('length', fns)), function () {
  39. var args = arguments;
  40. var context = this;
  41. return after.apply(context, _map(function (fn) {
  42. return fn.apply(context, args);
  43. }, fns));
  44. });
  45. });
  46. export default converge;