-
Notifications
You must be signed in to change notification settings - Fork 117
/
underscore.function.combinators.js
263 lines (220 loc) · 8.05 KB
/
underscore.function.combinators.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
// Underscore-contrib (underscore.function.combinators.js 0.3.0)
// (c) 2013 Michael Fogus, DocumentCloud and Investigative Reporters & Editors
// Underscore-contrib may be freely distributed under the MIT license.
(function() {
// Baseline setup
// --------------
// Establish the root object, `window` in the browser, or `require` it on the server.
if (typeof exports === 'object') {
_ = module.exports = require('underscore');
}
// Helpers
// -------
var existy = function(x) { return x != null; };
var truthy = function(x) { return (x !== false) && existy(x); };
var __reverse = [].reverse;
var __slice = [].slice;
var __map = [].map;
var curry2 = function (fun) {
return function curried (first, optionalLast) {
if (arguments.length === 1) {
return function (last) {
return fun(first, last);
};
}
else return fun(first, optionalLast);
};
};
var createPredicateApplicator = function (funcToInvoke /*, preds */) {
var preds = _(arguments).tail();
return function (objToCheck) {
var array = _(objToCheck).cat();
return _[funcToInvoke](array, function (e) {
return _[funcToInvoke](preds, function (p) {
return p(e);
});
});
};
};
// n.b. depends on underscore.function.arity.js
// n.b. depends on underscore.array.builders.js
// Takes a target function and a mapping function. Returns a function
// that applies the mapper to its arguments before evaluating the body.
function baseMapArgs (fun, mapFun) {
return _.arity(fun.length, function () {
return fun.apply(this, __map.call(arguments, mapFun));
});
}
// Mixing in the combinator functions
// ----------------------------------
_.mixin({
// Provide "always" alias for backwards compatibility
always: _.constant,
// Takes some number of functions, either as an array or variadically
// and returns a function that takes some value as its first argument
// and runs it through a pipeline of the original functions given.
pipeline: function(/*, funs */){
var funs = (_.isArray(arguments[0])) ? arguments[0] : arguments;
return function(seed) {
return _.reduce(funs,
function(l,r) { return r(l); },
seed);
};
},
// Composes a bunch of predicates into a single predicate that
// checks all elements of an array for conformance to all of the
// original predicates.
conjoin: _.partial(createPredicateApplicator, ('every')),
// Composes a bunch of predicates into a single predicate that
// checks all elements of an array for conformance to any of the
// original predicates.
disjoin: _.partial(createPredicateApplicator, 'some'),
// Takes a predicate-like and returns a comparator (-1,0,1).
comparator: function(fun) {
return function(x, y) {
if (truthy(fun(x, y)))
return -1;
else if (truthy(fun(y, x)))
return 1;
else
return 0;
};
},
// Returns a function that reverses the sense of a given predicate-like.
complement: function(pred) {
return function() {
return !pred.apply(this, arguments);
};
},
// Takes a function expecting varargs and
// returns a function that takes an array and
// uses its elements as the args to the original
// function
splat: function(fun) {
return function(array) {
return fun.apply(this, array);
};
},
// Takes a function expecting an array and returns
// a function that takes varargs and wraps all
// in an array that is passed to the original function.
unsplat: function(fun) {
var funLength = fun.length;
if (funLength < 1) {
return fun;
}
else if (funLength === 1) {
return function () {
return fun.call(this, __slice.call(arguments, 0));
};
}
else {
return function () {
var numberOfArgs = arguments.length,
namedArgs = __slice.call(arguments, 0, funLength - 1),
numberOfMissingNamedArgs = Math.max(funLength - numberOfArgs - 1, 0),
argPadding = new Array(numberOfMissingNamedArgs),
variadicArgs = __slice.call(arguments, fun.length - 1);
return fun.apply(this, namedArgs.concat(argPadding).concat([variadicArgs]));
};
}
},
// Same as unsplat, but the rest of the arguments are collected in the
// first parameter, e.g. unsplatl( function (args, callback) { ... ]})
unsplatl: function(fun) {
var funLength = fun.length;
if (funLength < 1) {
return fun;
}
else if (funLength === 1) {
return function () {
return fun.call(this, __slice.call(arguments, 0));
};
}
else {
return function () {
var numberOfArgs = arguments.length,
namedArgs = __slice.call(arguments, Math.max(numberOfArgs - funLength + 1, 0)),
variadicArgs = __slice.call(arguments, 0, Math.max(numberOfArgs - funLength + 1, 0));
return fun.apply(this, [variadicArgs].concat(namedArgs));
};
}
},
// map the arguments of a function
mapArgs: curry2(baseMapArgs),
// Returns a function that returns an array of the calls to each
// given function for some arguments.
juxt: function(/* funs */) {
var funs = arguments;
return function(/* args */) {
var args = arguments;
return _.map(funs, function(f) {
return f.apply(this, args);
}, this);
};
},
// Returns a function that protects a given function from receiving
// non-existy values. Each subsequent value provided to `fnull` acts
// as the default to the original function should a call receive non-existy
// values in the defaulted arg slots.
fnull: function(fun /*, defaults */) {
var defaults = _.rest(arguments);
return function(/*args*/) {
var args = _.toArray(arguments);
var sz = _.size(defaults);
for(var i = 0; i < sz; i++) {
if (!existy(args[i]))
args[i] = defaults[i];
}
return fun.apply(this, args);
};
},
// Flips the first two args of a function
flip2: function(fun) {
return function(/* args */) {
var flipped = __slice.call(arguments);
flipped[0] = arguments[1];
flipped[1] = arguments[0];
return fun.apply(this, flipped);
};
},
// Flips an arbitrary number of args of a function
flip: function(fun) {
return function(/* args */) {
var reversed = __reverse.call(arguments);
return fun.apply(this, reversed);
};
},
// Takes a method-style function (one which uses `this`) and pushes
// `this` into the argument list. The returned function uses its first
// argument as the receiver/context of the original function, and the rest
// of the arguments are used as the original's entire argument list.
functionalize: function(method) {
return function(ctx /*, args */) {
return method.apply(ctx, _.rest(arguments));
};
},
// Takes a function and pulls the first argument out of the argument
// list and into `this` position. The returned function calls the original
// with its receiver (`this`) prepending the argument list. The original
// is called with a receiver of `null`.
methodize: function(func) {
return function(/* args */) {
return func.apply(null, _.cons(this, arguments));
};
},
k: _.always,
t: _.pipeline
});
_.unsplatr = _.unsplat;
// map the arguments of a function, takes the mapping function
// first so it can be used as a combinator
_.mapArgsWith = curry2(_.flip(baseMapArgs));
// Returns function property of object by name, bound to object
_.bound = function(obj, fname) {
var fn = obj[fname];
if (!_.isFunction(fn))
throw new TypeError("Expected property to be a function");
return _.bind(fn, obj);
};
}).call(this);