UNPKG

1.88 kBJavaScriptView Raw
1var _curry2 =
2/*#__PURE__*/
3require("./internal/_curry2");
4
5var _isFunction =
6/*#__PURE__*/
7require("./internal/_isFunction");
8
9var curryN =
10/*#__PURE__*/
11require("./curryN");
12
13var toString =
14/*#__PURE__*/
15require("./toString");
16/**
17 * Turns a named method with a specified arity into a function that can be
18 * called directly supplied with arguments and a target object.
19 *
20 * The returned function is curried and accepts `arity + 1` parameters where
21 * the final parameter is the target object.
22 *
23 * @func
24 * @memberOf R
25 * @since v0.1.0
26 * @category Function
27 * @sig Number -> String -> (a -> b -> ... -> n -> Object -> *)
28 * @param {Number} arity Number of arguments the returned function should take
29 * before the target object.
30 * @param {String} method Name of any of the target object's methods to call.
31 * @return {Function} A new curried function.
32 * @see R.construct
33 * @example
34 *
35 * const sliceFrom = R.invoker(1, 'slice');
36 * sliceFrom(6, 'abcdefghijklm'); //=> 'ghijklm'
37 * const sliceFrom6 = R.invoker(2, 'slice')(6);
38 * sliceFrom6(8, 'abcdefghijklm'); //=> 'gh'
39 *
40 * const dog = {
41 * speak: async () => 'Woof!'
42 * };
43 * const speak = R.invoker(0, 'speak');
44 * speak(dog).then(console.log) //~> 'Woof!'
45 *
46 * @symb R.invoker(0, 'method')(o) = o['method']()
47 * @symb R.invoker(1, 'method')(a, o) = o['method'](a)
48 * @symb R.invoker(2, 'method')(a, b, o) = o['method'](a, b)
49 */
50
51
52var invoker =
53/*#__PURE__*/
54_curry2(function invoker(arity, method) {
55 return curryN(arity + 1, function () {
56 var target = arguments[arity];
57
58 if (target != null && _isFunction(target[method])) {
59 return target[method].apply(target, Array.prototype.slice.call(arguments, 0, arity));
60 }
61
62 throw new TypeError(toString(target) + ' does not have a method named "' + method + '"');
63 });
64});
65
66module.exports = invoker;
\No newline at end of file