UNPKG

2.07 kBJavaScriptView Raw
1var baseRest = require('./_baseRest'),
2 createWrap = require('./_createWrap'),
3 getHolder = require('./_getHolder'),
4 replaceHolders = require('./_replaceHolders');
5
6/** Used to compose bitmasks for function metadata. */
7var WRAP_BIND_FLAG = 1,
8 WRAP_BIND_KEY_FLAG = 2,
9 WRAP_PARTIAL_FLAG = 32;
10
11/**
12 * Creates a function that invokes the method at `object[key]` with `partials`
13 * prepended to the arguments it receives.
14 *
15 * This method differs from `_.bind` by allowing bound functions to reference
16 * methods that may be redefined or don't yet exist. See
17 * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)
18 * for more details.
19 *
20 * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic
21 * builds, may be used as a placeholder for partially applied arguments.
22 *
23 * @static
24 * @memberOf _
25 * @since 0.10.0
26 * @category Function
27 * @param {Object} object The object to invoke the method on.
28 * @param {string} key The key of the method.
29 * @param {...*} [partials] The arguments to be partially applied.
30 * @returns {Function} Returns the new bound function.
31 * @example
32 *
33 * var object = {
34 * 'user': 'fred',
35 * 'greet': function(greeting, punctuation) {
36 * return greeting + ' ' + this.user + punctuation;
37 * }
38 * };
39 *
40 * var bound = _.bindKey(object, 'greet', 'hi');
41 * bound('!');
42 * // => 'hi fred!'
43 *
44 * object.greet = function(greeting, punctuation) {
45 * return greeting + 'ya ' + this.user + punctuation;
46 * };
47 *
48 * bound('!');
49 * // => 'hiya fred!'
50 *
51 * // Bound with placeholders.
52 * var bound = _.bindKey(object, 'greet', _, '!');
53 * bound('hi');
54 * // => 'hiya fred!'
55 */
56var bindKey = baseRest(function(object, key, partials) {
57 var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG;
58 if (partials.length) {
59 var holders = replaceHolders(partials, getHolder(bindKey));
60 bitmask |= WRAP_PARTIAL_FLAG;
61 }
62 return createWrap(key, bitmask, object, partials, holders);
63});
64
65// Assign default placeholders.
66bindKey.placeholder = {};
67
68module.exports = bindKey;