-
Notifications
You must be signed in to change notification settings - Fork 394
/
Copy pathapply.js
70 lines (62 loc) · 1.85 KB
/
apply.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/** @license MIT License (c) copyright B Cavalier & J Hann */
/**
* apply.js
* Helper for using arguments-based and variadic callbacks with any
* {@link Promise} that resolves to an array.
*
* @author [email protected]
*/
(function(define) {
define(function() {
var toString = Object.prototype.toString;
/**
* Creates a function that accepts a function that takes individual
* arguments (it can be variadic, too), and returns a new function that
* takes a single array as its only param:
*
* function argBased(a, b, c) {
* return a + b + c;
* }
*
* argBased(1, 2, 3); // 6
*
* // Create an array-based version of argBased
* var arrayBased = apply(argBased);
* var inputs = [1, 2, 3];
*
* arrayBased(inputs); // 6
*
* With promises:
*
* var d = when.defer();
* d.promise.then(arrayBased);
*
* d.resolve([1, 2, 3]); // arrayBased called with args 1, 2, 3 -> 6
*
* @param f {Function} arguments-based function
*
* @returns {Function} a new function that accepts an array
*/
return function(f) {
/**
* @param array {Array} must be an array of arguments to use to apply the original function
*
* @returns the result of applying f with the arguments in array.
*/
return function(array) {
// It better be an array
if(toString.call(array) != '[object Array]') {
throw new Error('apply called with non-array arg');
}
return f.apply(null, array);
};
};
});
})(typeof define == 'function'
? define
: function (factory) { typeof module != 'undefined'
? (module.exports = factory())
: (this.when_apply = factory());
}
// Boilerplate for AMD, Node, and browser global
);