invoker.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import _curry2 from "./internal/_curry2.js";
  2. import _isFunction from "./internal/_isFunction.js";
  3. import curryN from "./curryN.js";
  4. import toString from "./toString.js";
  5. /**
  6. * Given an `arity` (Number) and a `name` (String) the `invoker` function
  7. * returns a curried function that takes `arity` arguments and a `context`
  8. * object. It will "invoke" the `name`'d function (a method) on the `context`
  9. * object.
  10. *
  11. * @func
  12. * @memberOf R
  13. * @since v0.1.0
  14. * @category Function
  15. * @sig Number -> String -> (a -> b -> ... -> n -> Object -> *)
  16. * @param {Number} arity Number of arguments the returned function should take
  17. * before the target object.
  18. * @param {String} method Name of any of the target object's methods to call.
  19. * @return {Function} A new curried function.
  20. * @see R.construct
  21. * @example
  22. * // A function with no arguments
  23. * const asJson = invoker(0, "json")
  24. * // Just like calling .then((response) => response.json())
  25. * fetch("http://example.com/index.json").then(asJson)
  26. *
  27. * // A function with one argument
  28. * const sliceFrom = invoker(1, 'slice');
  29. * sliceFrom(6, 'abcdefghijklm'); //=> 'ghijklm'
  30. *
  31. * // A function with two arguments
  32. * const sliceFrom6 = invoker(2, 'slice')(6);
  33. * sliceFrom6(8, 'abcdefghijklm'); //=> 'gh'
  34. *
  35. * // NOTE: You can't simply pass some of the arguments to the initial invoker function.
  36. * const firstCreditCardSection = invoker(2, "slice", 0, 4)
  37. * firstCreditCardSection("4242 4242 4242 4242") // => Function<...>
  38. *
  39. * // Since invoker returns a curried function, you may partially apply it to create the function you need.
  40. * const firstCreditCardSection = invoker(2, "slice")(0, 4)
  41. * firstCreditCardSection("4242 4242 4242 4242") // => "4242"
  42. *
  43. * @symb R.invoker(0, 'method')(o) = o['method']()
  44. * @symb R.invoker(1, 'method')(a, o) = o['method'](a)
  45. * @symb R.invoker(2, 'method')(a, b, o) = o['method'](a, b)
  46. */
  47. var invoker =
  48. /*#__PURE__*/
  49. _curry2(function invoker(arity, method) {
  50. return curryN(arity + 1, function () {
  51. var target = arguments[arity];
  52. if (target != null && _isFunction(target[method])) {
  53. return target[method].apply(target, Array.prototype.slice.call(arguments, 0, arity));
  54. }
  55. throw new TypeError(toString(target) + ' does not have a method named "' + method + '"');
  56. });
  57. });
  58. export default invoker;