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.

57 lines
1.9 KiB

4 years ago
  1. import _curry1 from "./internal/_curry1.js";
  2. import apply from "./apply.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. import keys from "./keys.js";
  8. import values from "./values.js"; // Use custom mapValues function to avoid issues with specs that include a "map" key and R.map
  9. // delegating calls to .map
  10. function mapValues(fn, obj) {
  11. return keys(obj).reduce(function (acc, key) {
  12. acc[key] = fn(obj[key]);
  13. return acc;
  14. }, {});
  15. }
  16. /**
  17. * Given a spec object recursively mapping properties to functions, creates a
  18. * function producing an object of the same structure, by mapping each property
  19. * to the result of calling its associated function with the supplied arguments.
  20. *
  21. * @func
  22. * @memberOf R
  23. * @since v0.20.0
  24. * @category Function
  25. * @sig {k: ((a, b, ..., m) -> v)} -> ((a, b, ..., m) -> {k: v})
  26. * @param {Object} spec an object recursively mapping properties to functions for
  27. * producing the values for these properties.
  28. * @return {Function} A function that returns an object of the same structure
  29. * as `spec', with each property set to the value returned by calling its
  30. * associated function with the supplied arguments.
  31. * @see R.converge, R.juxt
  32. * @example
  33. *
  34. * const getMetrics = R.applySpec({
  35. * sum: R.add,
  36. * nested: { mul: R.multiply }
  37. * });
  38. * getMetrics(2, 4); // => { sum: 6, nested: { mul: 8 } }
  39. * @symb R.applySpec({ x: f, y: { z: g } })(a, b) = { x: f(a, b), y: { z: g(a, b) } }
  40. */
  41. var applySpec =
  42. /*#__PURE__*/
  43. _curry1(function applySpec(spec) {
  44. spec = mapValues(function (v) {
  45. return typeof v == 'function' ? v : applySpec(v);
  46. }, spec);
  47. return curryN(reduce(max, 0, pluck('length', values(spec))), function () {
  48. var args = arguments;
  49. return mapValues(function (f) {
  50. return apply(f, args);
  51. }, spec);
  52. });
  53. });
  54. export default applySpec;