UNPKG

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