1 // Underscore.js 1.8.3 |
1 // Underscore.js 1.9.1 |
2 // http://underscorejs.org |
2 // http://underscorejs.org |
3 // (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors |
3 // (c) 2009-2018 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors |
4 // Underscore may be freely distributed under the MIT license. |
4 // Underscore may be freely distributed under the MIT license. |
5 |
5 |
6 (function() { |
6 (function() { |
7 |
7 |
8 // Baseline setup |
8 // Baseline setup |
9 // -------------- |
9 // -------------- |
10 |
10 |
11 // Establish the root object, `window` in the browser, or `exports` on the server. |
11 // Establish the root object, `window` (`self`) in the browser, `global` |
12 var root = this; |
12 // on the server, or `this` in some virtual machines. We use `self` |
|
13 // instead of `window` for `WebWorker` support. |
|
14 var root = typeof self == 'object' && self.self === self && self || |
|
15 typeof global == 'object' && global.global === global && global || |
|
16 this || |
|
17 {}; |
13 |
18 |
14 // Save the previous value of the `_` variable. |
19 // Save the previous value of the `_` variable. |
15 var previousUnderscore = root._; |
20 var previousUnderscore = root._; |
16 |
21 |
17 // Save bytes in the minified (but not gzipped) version: |
22 // Save bytes in the minified (but not gzipped) version: |
18 var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; |
23 var ArrayProto = Array.prototype, ObjProto = Object.prototype; |
|
24 var SymbolProto = typeof Symbol !== 'undefined' ? Symbol.prototype : null; |
19 |
25 |
20 // Create quick reference variables for speed access to core prototypes. |
26 // Create quick reference variables for speed access to core prototypes. |
21 var |
27 var push = ArrayProto.push, |
22 push = ArrayProto.push, |
28 slice = ArrayProto.slice, |
23 slice = ArrayProto.slice, |
29 toString = ObjProto.toString, |
24 toString = ObjProto.toString, |
30 hasOwnProperty = ObjProto.hasOwnProperty; |
25 hasOwnProperty = ObjProto.hasOwnProperty; |
|
26 |
31 |
27 // All **ECMAScript 5** native function implementations that we hope to use |
32 // All **ECMAScript 5** native function implementations that we hope to use |
28 // are declared here. |
33 // are declared here. |
29 var |
34 var nativeIsArray = Array.isArray, |
30 nativeIsArray = Array.isArray, |
35 nativeKeys = Object.keys, |
31 nativeKeys = Object.keys, |
36 nativeCreate = Object.create; |
32 nativeBind = FuncProto.bind, |
|
33 nativeCreate = Object.create; |
|
34 |
37 |
35 // Naked function reference for surrogate-prototype-swapping. |
38 // Naked function reference for surrogate-prototype-swapping. |
36 var Ctor = function(){}; |
39 var Ctor = function(){}; |
37 |
40 |
38 // Create a safe reference to the Underscore object for use below. |
41 // Create a safe reference to the Underscore object for use below. |
41 if (!(this instanceof _)) return new _(obj); |
44 if (!(this instanceof _)) return new _(obj); |
42 this._wrapped = obj; |
45 this._wrapped = obj; |
43 }; |
46 }; |
44 |
47 |
45 // Export the Underscore object for **Node.js**, with |
48 // Export the Underscore object for **Node.js**, with |
46 // backwards-compatibility for the old `require()` API. If we're in |
49 // backwards-compatibility for their old module API. If we're in |
47 // the browser, add `_` as a global object. |
50 // the browser, add `_` as a global object. |
48 if (typeof exports !== 'undefined') { |
51 // (`nodeType` is checked to ensure that `module` |
49 if (typeof module !== 'undefined' && module.exports) { |
52 // and `exports` are not HTML elements.) |
|
53 if (typeof exports != 'undefined' && !exports.nodeType) { |
|
54 if (typeof module != 'undefined' && !module.nodeType && module.exports) { |
50 exports = module.exports = _; |
55 exports = module.exports = _; |
51 } |
56 } |
52 exports._ = _; |
57 exports._ = _; |
53 } else { |
58 } else { |
54 root._ = _; |
59 root._ = _; |
55 } |
60 } |
56 |
61 |
57 // Current version. |
62 // Current version. |
58 _.VERSION = '1.8.3'; |
63 _.VERSION = '1.9.1'; |
59 |
64 |
60 // Internal function that returns an efficient (for current engines) version |
65 // Internal function that returns an efficient (for current engines) version |
61 // of the passed-in callback, to be repeatedly applied in other Underscore |
66 // of the passed-in callback, to be repeatedly applied in other Underscore |
62 // functions. |
67 // functions. |
63 var optimizeCb = function(func, context, argCount) { |
68 var optimizeCb = function(func, context, argCount) { |
64 if (context === void 0) return func; |
69 if (context === void 0) return func; |
65 switch (argCount == null ? 3 : argCount) { |
70 switch (argCount == null ? 3 : argCount) { |
66 case 1: return function(value) { |
71 case 1: return function(value) { |
67 return func.call(context, value); |
72 return func.call(context, value); |
68 }; |
73 }; |
69 case 2: return function(value, other) { |
74 // The 2-argument case is omitted because we’re not using it. |
70 return func.call(context, value, other); |
|
71 }; |
|
72 case 3: return function(value, index, collection) { |
75 case 3: return function(value, index, collection) { |
73 return func.call(context, value, index, collection); |
76 return func.call(context, value, index, collection); |
74 }; |
77 }; |
75 case 4: return function(accumulator, value, index, collection) { |
78 case 4: return function(accumulator, value, index, collection) { |
76 return func.call(context, accumulator, value, index, collection); |
79 return func.call(context, accumulator, value, index, collection); |
79 return function() { |
82 return function() { |
80 return func.apply(context, arguments); |
83 return func.apply(context, arguments); |
81 }; |
84 }; |
82 }; |
85 }; |
83 |
86 |
84 // A mostly-internal function to generate callbacks that can be applied |
87 var builtinIteratee; |
85 // to each element in a collection, returning the desired result — either |
88 |
86 // identity, an arbitrary callback, a property matcher, or a property accessor. |
89 // An internal function to generate callbacks that can be applied to each |
|
90 // element in a collection, returning the desired result — either `identity`, |
|
91 // an arbitrary callback, a property matcher, or a property accessor. |
87 var cb = function(value, context, argCount) { |
92 var cb = function(value, context, argCount) { |
|
93 if (_.iteratee !== builtinIteratee) return _.iteratee(value, context); |
88 if (value == null) return _.identity; |
94 if (value == null) return _.identity; |
89 if (_.isFunction(value)) return optimizeCb(value, context, argCount); |
95 if (_.isFunction(value)) return optimizeCb(value, context, argCount); |
90 if (_.isObject(value)) return _.matcher(value); |
96 if (_.isObject(value) && !_.isArray(value)) return _.matcher(value); |
91 return _.property(value); |
97 return _.property(value); |
92 }; |
98 }; |
93 _.iteratee = function(value, context) { |
99 |
|
100 // External wrapper for our callback generator. Users may customize |
|
101 // `_.iteratee` if they want additional predicate/iteratee shorthand styles. |
|
102 // This abstraction hides the internal-only argCount argument. |
|
103 _.iteratee = builtinIteratee = function(value, context) { |
94 return cb(value, context, Infinity); |
104 return cb(value, context, Infinity); |
95 }; |
105 }; |
96 |
106 |
97 // An internal function for creating assigner functions. |
107 // Some functions take a variable number of arguments, or a few expected |
98 var createAssigner = function(keysFunc, undefinedOnly) { |
108 // arguments at the beginning and then a variable number of values to operate |
99 return function(obj) { |
109 // on. This helper accumulates all remaining arguments past the function’s |
100 var length = arguments.length; |
110 // argument length (or an explicit `startIndex`), into an array that becomes |
101 if (length < 2 || obj == null) return obj; |
111 // the last argument. Similar to ES6’s "rest parameter". |
102 for (var index = 1; index < length; index++) { |
112 var restArguments = function(func, startIndex) { |
103 var source = arguments[index], |
113 startIndex = startIndex == null ? func.length - 1 : +startIndex; |
104 keys = keysFunc(source), |
114 return function() { |
105 l = keys.length; |
115 var length = Math.max(arguments.length - startIndex, 0), |
106 for (var i = 0; i < l; i++) { |
116 rest = Array(length), |
107 var key = keys[i]; |
117 index = 0; |
108 if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key]; |
118 for (; index < length; index++) { |
109 } |
119 rest[index] = arguments[index + startIndex]; |
110 } |
120 } |
111 return obj; |
121 switch (startIndex) { |
|
122 case 0: return func.call(this, rest); |
|
123 case 1: return func.call(this, arguments[0], rest); |
|
124 case 2: return func.call(this, arguments[0], arguments[1], rest); |
|
125 } |
|
126 var args = Array(startIndex + 1); |
|
127 for (index = 0; index < startIndex; index++) { |
|
128 args[index] = arguments[index]; |
|
129 } |
|
130 args[startIndex] = rest; |
|
131 return func.apply(this, args); |
112 }; |
132 }; |
113 }; |
133 }; |
114 |
134 |
115 // An internal function for creating a new object that inherits from another. |
135 // An internal function for creating a new object that inherits from another. |
116 var baseCreate = function(prototype) { |
136 var baseCreate = function(prototype) { |
120 var result = new Ctor; |
140 var result = new Ctor; |
121 Ctor.prototype = null; |
141 Ctor.prototype = null; |
122 return result; |
142 return result; |
123 }; |
143 }; |
124 |
144 |
125 var property = function(key) { |
145 var shallowProperty = function(key) { |
126 return function(obj) { |
146 return function(obj) { |
127 return obj == null ? void 0 : obj[key]; |
147 return obj == null ? void 0 : obj[key]; |
128 }; |
148 }; |
129 }; |
149 }; |
130 |
150 |
|
151 var has = function(obj, path) { |
|
152 return obj != null && hasOwnProperty.call(obj, path); |
|
153 } |
|
154 |
|
155 var deepGet = function(obj, path) { |
|
156 var length = path.length; |
|
157 for (var i = 0; i < length; i++) { |
|
158 if (obj == null) return void 0; |
|
159 obj = obj[path[i]]; |
|
160 } |
|
161 return length ? obj : void 0; |
|
162 }; |
|
163 |
131 // Helper for collection methods to determine whether a collection |
164 // Helper for collection methods to determine whether a collection |
132 // should be iterated as an array or as an object |
165 // should be iterated as an array or as an object. |
133 // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength |
166 // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength |
134 // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094 |
167 // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094 |
135 var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1; |
168 var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1; |
136 var getLength = property('length'); |
169 var getLength = shallowProperty('length'); |
137 var isArrayLike = function(collection) { |
170 var isArrayLike = function(collection) { |
138 var length = getLength(collection); |
171 var length = getLength(collection); |
139 return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX; |
172 return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX; |
140 }; |
173 }; |
141 |
174 |
173 } |
206 } |
174 return results; |
207 return results; |
175 }; |
208 }; |
176 |
209 |
177 // Create a reducing function iterating left or right. |
210 // Create a reducing function iterating left or right. |
178 function createReduce(dir) { |
211 var createReduce = function(dir) { |
179 // Optimized iterator function as using arguments.length |
212 // Wrap code that reassigns argument variables in a separate function than |
180 // in the main function will deoptimize the, see #1991. |
213 // the one that accesses `arguments.length` to avoid a perf hit. (#1991) |
181 function iterator(obj, iteratee, memo, keys, index, length) { |
214 var reducer = function(obj, iteratee, memo, initial) { |
|
215 var keys = !isArrayLike(obj) && _.keys(obj), |
|
216 length = (keys || obj).length, |
|
217 index = dir > 0 ? 0 : length - 1; |
|
218 if (!initial) { |
|
219 memo = obj[keys ? keys[index] : index]; |
|
220 index += dir; |
|
221 } |
182 for (; index >= 0 && index < length; index += dir) { |
222 for (; index >= 0 && index < length; index += dir) { |
183 var currentKey = keys ? keys[index] : index; |
223 var currentKey = keys ? keys[index] : index; |
184 memo = iteratee(memo, obj[currentKey], currentKey, obj); |
224 memo = iteratee(memo, obj[currentKey], currentKey, obj); |
185 } |
225 } |
186 return memo; |
226 return memo; |
187 } |
227 }; |
188 |
228 |
189 return function(obj, iteratee, memo, context) { |
229 return function(obj, iteratee, memo, context) { |
190 iteratee = optimizeCb(iteratee, context, 4); |
230 var initial = arguments.length >= 3; |
191 var keys = !isArrayLike(obj) && _.keys(obj), |
231 return reducer(obj, optimizeCb(iteratee, context, 4), memo, initial); |
192 length = (keys || obj).length, |
232 }; |
193 index = dir > 0 ? 0 : length - 1; |
233 }; |
194 // Determine the initial value if none is provided. |
|
195 if (arguments.length < 3) { |
|
196 memo = obj[keys ? keys[index] : index]; |
|
197 index += dir; |
|
198 } |
|
199 return iterator(obj, iteratee, memo, keys, index, length); |
|
200 }; |
|
201 } |
|
202 |
234 |
203 // **Reduce** builds up a single result from a list of values, aka `inject`, |
235 // **Reduce** builds up a single result from a list of values, aka `inject`, |
204 // or `foldl`. |
236 // or `foldl`. |
205 _.reduce = _.foldl = _.inject = createReduce(1); |
237 _.reduce = _.foldl = _.inject = createReduce(1); |
206 |
238 |
207 // The right-associative version of reduce, also known as `foldr`. |
239 // The right-associative version of reduce, also known as `foldr`. |
208 _.reduceRight = _.foldr = createReduce(-1); |
240 _.reduceRight = _.foldr = createReduce(-1); |
209 |
241 |
210 // Return the first value which passes a truth test. Aliased as `detect`. |
242 // Return the first value which passes a truth test. Aliased as `detect`. |
211 _.find = _.detect = function(obj, predicate, context) { |
243 _.find = _.detect = function(obj, predicate, context) { |
212 var key; |
244 var keyFinder = isArrayLike(obj) ? _.findIndex : _.findKey; |
213 if (isArrayLike(obj)) { |
245 var key = keyFinder(obj, predicate, context); |
214 key = _.findIndex(obj, predicate, context); |
|
215 } else { |
|
216 key = _.findKey(obj, predicate, context); |
|
217 } |
|
218 if (key !== void 0 && key !== -1) return obj[key]; |
246 if (key !== void 0 && key !== -1) return obj[key]; |
219 }; |
247 }; |
220 |
248 |
221 // Return all the elements that pass a truth test. |
249 // Return all the elements that pass a truth test. |
222 // Aliased as `select`. |
250 // Aliased as `select`. |
267 if (typeof fromIndex != 'number' || guard) fromIndex = 0; |
295 if (typeof fromIndex != 'number' || guard) fromIndex = 0; |
268 return _.indexOf(obj, item, fromIndex) >= 0; |
296 return _.indexOf(obj, item, fromIndex) >= 0; |
269 }; |
297 }; |
270 |
298 |
271 // Invoke a method (with arguments) on every item in a collection. |
299 // Invoke a method (with arguments) on every item in a collection. |
272 _.invoke = function(obj, method) { |
300 _.invoke = restArguments(function(obj, path, args) { |
273 var args = slice.call(arguments, 2); |
301 var contextPath, func; |
274 var isFunc = _.isFunction(method); |
302 if (_.isFunction(path)) { |
275 return _.map(obj, function(value) { |
303 func = path; |
276 var func = isFunc ? method : value[method]; |
304 } else if (_.isArray(path)) { |
277 return func == null ? func : func.apply(value, args); |
305 contextPath = path.slice(0, -1); |
|
306 path = path[path.length - 1]; |
|
307 } |
|
308 return _.map(obj, function(context) { |
|
309 var method = func; |
|
310 if (!method) { |
|
311 if (contextPath && contextPath.length) { |
|
312 context = deepGet(context, contextPath); |
|
313 } |
|
314 if (context == null) return void 0; |
|
315 method = context[path]; |
|
316 } |
|
317 return method == null ? method : method.apply(context, args); |
278 }); |
318 }); |
279 }; |
319 }); |
280 |
320 |
281 // Convenience version of a common use case of `map`: fetching a property. |
321 // Convenience version of a common use case of `map`: fetching a property. |
282 _.pluck = function(obj, key) { |
322 _.pluck = function(obj, key) { |
283 return _.map(obj, _.property(key)); |
323 return _.map(obj, _.property(key)); |
284 }; |
324 }; |
297 |
337 |
298 // Return the maximum element (or element-based computation). |
338 // Return the maximum element (or element-based computation). |
299 _.max = function(obj, iteratee, context) { |
339 _.max = function(obj, iteratee, context) { |
300 var result = -Infinity, lastComputed = -Infinity, |
340 var result = -Infinity, lastComputed = -Infinity, |
301 value, computed; |
341 value, computed; |
302 if (iteratee == null && obj != null) { |
342 if (iteratee == null || typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null) { |
303 obj = isArrayLike(obj) ? obj : _.values(obj); |
343 obj = isArrayLike(obj) ? obj : _.values(obj); |
304 for (var i = 0, length = obj.length; i < length; i++) { |
344 for (var i = 0, length = obj.length; i < length; i++) { |
305 value = obj[i]; |
345 value = obj[i]; |
306 if (value > result) { |
346 if (value != null && value > result) { |
307 result = value; |
347 result = value; |
308 } |
348 } |
309 } |
349 } |
310 } else { |
350 } else { |
311 iteratee = cb(iteratee, context); |
351 iteratee = cb(iteratee, context); |
312 _.each(obj, function(value, index, list) { |
352 _.each(obj, function(v, index, list) { |
313 computed = iteratee(value, index, list); |
353 computed = iteratee(v, index, list); |
314 if (computed > lastComputed || computed === -Infinity && result === -Infinity) { |
354 if (computed > lastComputed || computed === -Infinity && result === -Infinity) { |
315 result = value; |
355 result = v; |
316 lastComputed = computed; |
356 lastComputed = computed; |
317 } |
357 } |
318 }); |
358 }); |
319 } |
359 } |
320 return result; |
360 return result; |
322 |
362 |
323 // Return the minimum element (or element-based computation). |
363 // Return the minimum element (or element-based computation). |
324 _.min = function(obj, iteratee, context) { |
364 _.min = function(obj, iteratee, context) { |
325 var result = Infinity, lastComputed = Infinity, |
365 var result = Infinity, lastComputed = Infinity, |
326 value, computed; |
366 value, computed; |
327 if (iteratee == null && obj != null) { |
367 if (iteratee == null || typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null) { |
328 obj = isArrayLike(obj) ? obj : _.values(obj); |
368 obj = isArrayLike(obj) ? obj : _.values(obj); |
329 for (var i = 0, length = obj.length; i < length; i++) { |
369 for (var i = 0, length = obj.length; i < length; i++) { |
330 value = obj[i]; |
370 value = obj[i]; |
331 if (value < result) { |
371 if (value != null && value < result) { |
332 result = value; |
372 result = value; |
333 } |
373 } |
334 } |
374 } |
335 } else { |
375 } else { |
336 iteratee = cb(iteratee, context); |
376 iteratee = cb(iteratee, context); |
337 _.each(obj, function(value, index, list) { |
377 _.each(obj, function(v, index, list) { |
338 computed = iteratee(value, index, list); |
378 computed = iteratee(v, index, list); |
339 if (computed < lastComputed || computed === Infinity && result === Infinity) { |
379 if (computed < lastComputed || computed === Infinity && result === Infinity) { |
340 result = value; |
380 result = v; |
341 lastComputed = computed; |
381 lastComputed = computed; |
342 } |
382 } |
343 }); |
383 }); |
344 } |
384 } |
345 return result; |
385 return result; |
346 }; |
386 }; |
347 |
387 |
348 // Shuffle a collection, using the modern version of the |
388 // Shuffle a collection. |
|
389 _.shuffle = function(obj) { |
|
390 return _.sample(obj, Infinity); |
|
391 }; |
|
392 |
|
393 // Sample **n** random values from a collection using the modern version of the |
349 // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). |
394 // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). |
350 _.shuffle = function(obj) { |
|
351 var set = isArrayLike(obj) ? obj : _.values(obj); |
|
352 var length = set.length; |
|
353 var shuffled = Array(length); |
|
354 for (var index = 0, rand; index < length; index++) { |
|
355 rand = _.random(0, index); |
|
356 if (rand !== index) shuffled[index] = shuffled[rand]; |
|
357 shuffled[rand] = set[index]; |
|
358 } |
|
359 return shuffled; |
|
360 }; |
|
361 |
|
362 // Sample **n** random values from a collection. |
|
363 // If **n** is not specified, returns a single random element. |
395 // If **n** is not specified, returns a single random element. |
364 // The internal `guard` argument allows it to work with `map`. |
396 // The internal `guard` argument allows it to work with `map`. |
365 _.sample = function(obj, n, guard) { |
397 _.sample = function(obj, n, guard) { |
366 if (n == null || guard) { |
398 if (n == null || guard) { |
367 if (!isArrayLike(obj)) obj = _.values(obj); |
399 if (!isArrayLike(obj)) obj = _.values(obj); |
368 return obj[_.random(obj.length - 1)]; |
400 return obj[_.random(obj.length - 1)]; |
369 } |
401 } |
370 return _.shuffle(obj).slice(0, Math.max(0, n)); |
402 var sample = isArrayLike(obj) ? _.clone(obj) : _.values(obj); |
|
403 var length = getLength(sample); |
|
404 n = Math.max(Math.min(n, length), 0); |
|
405 var last = length - 1; |
|
406 for (var index = 0; index < n; index++) { |
|
407 var rand = _.random(index, last); |
|
408 var temp = sample[index]; |
|
409 sample[index] = sample[rand]; |
|
410 sample[rand] = temp; |
|
411 } |
|
412 return sample.slice(0, n); |
371 }; |
413 }; |
372 |
414 |
373 // Sort the object's values by a criterion produced by an iteratee. |
415 // Sort the object's values by a criterion produced by an iteratee. |
374 _.sortBy = function(obj, iteratee, context) { |
416 _.sortBy = function(obj, iteratee, context) { |
|
417 var index = 0; |
375 iteratee = cb(iteratee, context); |
418 iteratee = cb(iteratee, context); |
376 return _.pluck(_.map(obj, function(value, index, list) { |
419 return _.pluck(_.map(obj, function(value, key, list) { |
377 return { |
420 return { |
378 value: value, |
421 value: value, |
379 index: index, |
422 index: index++, |
380 criteria: iteratee(value, index, list) |
423 criteria: iteratee(value, key, list) |
381 }; |
424 }; |
382 }).sort(function(left, right) { |
425 }).sort(function(left, right) { |
383 var a = left.criteria; |
426 var a = left.criteria; |
384 var b = right.criteria; |
427 var b = right.criteria; |
385 if (a !== b) { |
428 if (a !== b) { |
389 return left.index - right.index; |
432 return left.index - right.index; |
390 }), 'value'); |
433 }), 'value'); |
391 }; |
434 }; |
392 |
435 |
393 // An internal function used for aggregate "group by" operations. |
436 // An internal function used for aggregate "group by" operations. |
394 var group = function(behavior) { |
437 var group = function(behavior, partition) { |
395 return function(obj, iteratee, context) { |
438 return function(obj, iteratee, context) { |
396 var result = {}; |
439 var result = partition ? [[], []] : {}; |
397 iteratee = cb(iteratee, context); |
440 iteratee = cb(iteratee, context); |
398 _.each(obj, function(value, index) { |
441 _.each(obj, function(value, index) { |
399 var key = iteratee(value, index, obj); |
442 var key = iteratee(value, index, obj); |
400 behavior(result, value, key); |
443 behavior(result, value, key); |
401 }); |
444 }); |
417 |
460 |
418 // Counts instances of an object that group by a certain criterion. Pass |
461 // Counts instances of an object that group by a certain criterion. Pass |
419 // either a string attribute to count by, or a function that returns the |
462 // either a string attribute to count by, or a function that returns the |
420 // criterion. |
463 // criterion. |
421 _.countBy = group(function(result, value, key) { |
464 _.countBy = group(function(result, value, key) { |
422 if (_.has(result, key)) result[key]++; else result[key] = 1; |
465 if (has(result, key)) result[key]++; else result[key] = 1; |
423 }); |
466 }); |
424 |
467 |
|
468 var reStrSymbol = /[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g; |
425 // Safely create a real, live array from anything iterable. |
469 // Safely create a real, live array from anything iterable. |
426 _.toArray = function(obj) { |
470 _.toArray = function(obj) { |
427 if (!obj) return []; |
471 if (!obj) return []; |
428 if (_.isArray(obj)) return slice.call(obj); |
472 if (_.isArray(obj)) return slice.call(obj); |
|
473 if (_.isString(obj)) { |
|
474 // Keep surrogate pair characters together |
|
475 return obj.match(reStrSymbol); |
|
476 } |
429 if (isArrayLike(obj)) return _.map(obj, _.identity); |
477 if (isArrayLike(obj)) return _.map(obj, _.identity); |
430 return _.values(obj); |
478 return _.values(obj); |
431 }; |
479 }; |
432 |
480 |
433 // Return the number of elements in an object. |
481 // Return the number of elements in an object. |
436 return isArrayLike(obj) ? obj.length : _.keys(obj).length; |
484 return isArrayLike(obj) ? obj.length : _.keys(obj).length; |
437 }; |
485 }; |
438 |
486 |
439 // Split a collection into two arrays: one whose elements all satisfy the given |
487 // Split a collection into two arrays: one whose elements all satisfy the given |
440 // predicate, and one whose elements all do not satisfy the predicate. |
488 // predicate, and one whose elements all do not satisfy the predicate. |
441 _.partition = function(obj, predicate, context) { |
489 _.partition = group(function(result, value, pass) { |
442 predicate = cb(predicate, context); |
490 result[pass ? 0 : 1].push(value); |
443 var pass = [], fail = []; |
491 }, true); |
444 _.each(obj, function(value, key, obj) { |
|
445 (predicate(value, key, obj) ? pass : fail).push(value); |
|
446 }); |
|
447 return [pass, fail]; |
|
448 }; |
|
449 |
492 |
450 // Array Functions |
493 // Array Functions |
451 // --------------- |
494 // --------------- |
452 |
495 |
453 // Get the first element of an array. Passing **n** will return the first N |
496 // Get the first element of an array. Passing **n** will return the first N |
454 // values in the array. Aliased as `head` and `take`. The **guard** check |
497 // values in the array. Aliased as `head` and `take`. The **guard** check |
455 // allows it to work with `_.map`. |
498 // allows it to work with `_.map`. |
456 _.first = _.head = _.take = function(array, n, guard) { |
499 _.first = _.head = _.take = function(array, n, guard) { |
457 if (array == null) return void 0; |
500 if (array == null || array.length < 1) return n == null ? void 0 : []; |
458 if (n == null || guard) return array[0]; |
501 if (n == null || guard) return array[0]; |
459 return _.initial(array, array.length - n); |
502 return _.initial(array, array.length - n); |
460 }; |
503 }; |
461 |
504 |
462 // Returns everything but the last entry of the array. Especially useful on |
505 // Returns everything but the last entry of the array. Especially useful on |
481 return slice.call(array, n == null || guard ? 1 : n); |
524 return slice.call(array, n == null || guard ? 1 : n); |
482 }; |
525 }; |
483 |
526 |
484 // Trim out all falsy values from an array. |
527 // Trim out all falsy values from an array. |
485 _.compact = function(array) { |
528 _.compact = function(array) { |
486 return _.filter(array, _.identity); |
529 return _.filter(array, Boolean); |
487 }; |
530 }; |
488 |
531 |
489 // Internal implementation of a recursive `flatten` function. |
532 // Internal implementation of a recursive `flatten` function. |
490 var flatten = function(input, shallow, strict, startIndex) { |
533 var flatten = function(input, shallow, strict, output) { |
491 var output = [], idx = 0; |
534 output = output || []; |
492 for (var i = startIndex || 0, length = getLength(input); i < length; i++) { |
535 var idx = output.length; |
|
536 for (var i = 0, length = getLength(input); i < length; i++) { |
493 var value = input[i]; |
537 var value = input[i]; |
494 if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) { |
538 if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) { |
495 //flatten current level of array or arguments object |
539 // Flatten current level of array or arguments object. |
496 if (!shallow) value = flatten(value, shallow, strict); |
540 if (shallow) { |
497 var j = 0, len = value.length; |
541 var j = 0, len = value.length; |
498 output.length += len; |
542 while (j < len) output[idx++] = value[j++]; |
499 while (j < len) { |
543 } else { |
500 output[idx++] = value[j++]; |
544 flatten(value, shallow, strict, output); |
|
545 idx = output.length; |
501 } |
546 } |
502 } else if (!strict) { |
547 } else if (!strict) { |
503 output[idx++] = value; |
548 output[idx++] = value; |
504 } |
549 } |
505 } |
550 } |
510 _.flatten = function(array, shallow) { |
555 _.flatten = function(array, shallow) { |
511 return flatten(array, shallow, false); |
556 return flatten(array, shallow, false); |
512 }; |
557 }; |
513 |
558 |
514 // Return a version of the array that does not contain the specified value(s). |
559 // Return a version of the array that does not contain the specified value(s). |
515 _.without = function(array) { |
560 _.without = restArguments(function(array, otherArrays) { |
516 return _.difference(array, slice.call(arguments, 1)); |
561 return _.difference(array, otherArrays); |
517 }; |
562 }); |
518 |
563 |
519 // Produce a duplicate-free version of the array. If the array has already |
564 // Produce a duplicate-free version of the array. If the array has already |
520 // been sorted, you have the option of using a faster algorithm. |
565 // been sorted, you have the option of using a faster algorithm. |
|
566 // The faster algorithm will not work with an iteratee if the iteratee |
|
567 // is not a one-to-one function, so providing an iteratee will disable |
|
568 // the faster algorithm. |
521 // Aliased as `unique`. |
569 // Aliased as `unique`. |
522 _.uniq = _.unique = function(array, isSorted, iteratee, context) { |
570 _.uniq = _.unique = function(array, isSorted, iteratee, context) { |
523 if (!_.isBoolean(isSorted)) { |
571 if (!_.isBoolean(isSorted)) { |
524 context = iteratee; |
572 context = iteratee; |
525 iteratee = isSorted; |
573 iteratee = isSorted; |
546 return result; |
594 return result; |
547 }; |
595 }; |
548 |
596 |
549 // Produce an array that contains the union: each distinct element from all of |
597 // Produce an array that contains the union: each distinct element from all of |
550 // the passed-in arrays. |
598 // the passed-in arrays. |
551 _.union = function() { |
599 _.union = restArguments(function(arrays) { |
552 return _.uniq(flatten(arguments, true, true)); |
600 return _.uniq(flatten(arrays, true, true)); |
553 }; |
601 }); |
554 |
602 |
555 // Produce an array that contains every item shared between all the |
603 // Produce an array that contains every item shared between all the |
556 // passed-in arrays. |
604 // passed-in arrays. |
557 _.intersection = function(array) { |
605 _.intersection = function(array) { |
558 var result = []; |
606 var result = []; |
559 var argsLength = arguments.length; |
607 var argsLength = arguments.length; |
560 for (var i = 0, length = getLength(array); i < length; i++) { |
608 for (var i = 0, length = getLength(array); i < length; i++) { |
561 var item = array[i]; |
609 var item = array[i]; |
562 if (_.contains(result, item)) continue; |
610 if (_.contains(result, item)) continue; |
563 for (var j = 1; j < argsLength; j++) { |
611 var j; |
|
612 for (j = 1; j < argsLength; j++) { |
564 if (!_.contains(arguments[j], item)) break; |
613 if (!_.contains(arguments[j], item)) break; |
565 } |
614 } |
566 if (j === argsLength) result.push(item); |
615 if (j === argsLength) result.push(item); |
567 } |
616 } |
568 return result; |
617 return result; |
569 }; |
618 }; |
570 |
619 |
571 // Take the difference between one array and a number of other arrays. |
620 // Take the difference between one array and a number of other arrays. |
572 // Only the elements present in just the first array will remain. |
621 // Only the elements present in just the first array will remain. |
573 _.difference = function(array) { |
622 _.difference = restArguments(function(array, rest) { |
574 var rest = flatten(arguments, true, true, 1); |
623 rest = flatten(rest, true, true); |
575 return _.filter(array, function(value){ |
624 return _.filter(array, function(value){ |
576 return !_.contains(rest, value); |
625 return !_.contains(rest, value); |
577 }); |
626 }); |
578 }; |
627 }); |
579 |
|
580 // Zip together multiple lists into a single array -- elements that share |
|
581 // an index go together. |
|
582 _.zip = function() { |
|
583 return _.unzip(arguments); |
|
584 }; |
|
585 |
628 |
586 // Complement of _.zip. Unzip accepts an array of arrays and groups |
629 // Complement of _.zip. Unzip accepts an array of arrays and groups |
587 // each array's elements on shared indices |
630 // each array's elements on shared indices. |
588 _.unzip = function(array) { |
631 _.unzip = function(array) { |
589 var length = array && _.max(array, getLength).length || 0; |
632 var length = array && _.max(array, getLength).length || 0; |
590 var result = Array(length); |
633 var result = Array(length); |
591 |
634 |
592 for (var index = 0; index < length; index++) { |
635 for (var index = 0; index < length; index++) { |
593 result[index] = _.pluck(array, index); |
636 result[index] = _.pluck(array, index); |
594 } |
637 } |
595 return result; |
638 return result; |
596 }; |
639 }; |
597 |
640 |
|
641 // Zip together multiple lists into a single array -- elements that share |
|
642 // an index go together. |
|
643 _.zip = restArguments(_.unzip); |
|
644 |
598 // Converts lists into objects. Pass either a single array of `[key, value]` |
645 // Converts lists into objects. Pass either a single array of `[key, value]` |
599 // pairs, or two parallel arrays of the same length -- one of keys, and one of |
646 // pairs, or two parallel arrays of the same length -- one of keys, and one of |
600 // the corresponding values. |
647 // the corresponding values. Passing by pairs is the reverse of _.pairs. |
601 _.object = function(list, values) { |
648 _.object = function(list, values) { |
602 var result = {}; |
649 var result = {}; |
603 for (var i = 0, length = getLength(list); i < length; i++) { |
650 for (var i = 0, length = getLength(list); i < length; i++) { |
604 if (values) { |
651 if (values) { |
605 result[list[i]] = values[i]; |
652 result[list[i]] = values[i]; |
608 } |
655 } |
609 } |
656 } |
610 return result; |
657 return result; |
611 }; |
658 }; |
612 |
659 |
613 // Generator function to create the findIndex and findLastIndex functions |
660 // Generator function to create the findIndex and findLastIndex functions. |
614 function createPredicateIndexFinder(dir) { |
661 var createPredicateIndexFinder = function(dir) { |
615 return function(array, predicate, context) { |
662 return function(array, predicate, context) { |
616 predicate = cb(predicate, context); |
663 predicate = cb(predicate, context); |
617 var length = getLength(array); |
664 var length = getLength(array); |
618 var index = dir > 0 ? 0 : length - 1; |
665 var index = dir > 0 ? 0 : length - 1; |
619 for (; index >= 0 && index < length; index += dir) { |
666 for (; index >= 0 && index < length; index += dir) { |
620 if (predicate(array[index], index, array)) return index; |
667 if (predicate(array[index], index, array)) return index; |
621 } |
668 } |
622 return -1; |
669 return -1; |
623 }; |
670 }; |
624 } |
671 }; |
625 |
672 |
626 // Returns the first index on an array-like that passes a predicate test |
673 // Returns the first index on an array-like that passes a predicate test. |
627 _.findIndex = createPredicateIndexFinder(1); |
674 _.findIndex = createPredicateIndexFinder(1); |
628 _.findLastIndex = createPredicateIndexFinder(-1); |
675 _.findLastIndex = createPredicateIndexFinder(-1); |
629 |
676 |
630 // Use a comparator function to figure out the smallest index at which |
677 // Use a comparator function to figure out the smallest index at which |
631 // an object should be inserted so as to maintain order. Uses binary search. |
678 // an object should be inserted so as to maintain order. Uses binary search. |
638 if (iteratee(array[mid]) < value) low = mid + 1; else high = mid; |
685 if (iteratee(array[mid]) < value) low = mid + 1; else high = mid; |
639 } |
686 } |
640 return low; |
687 return low; |
641 }; |
688 }; |
642 |
689 |
643 // Generator function to create the indexOf and lastIndexOf functions |
690 // Generator function to create the indexOf and lastIndexOf functions. |
644 function createIndexFinder(dir, predicateFind, sortedIndex) { |
691 var createIndexFinder = function(dir, predicateFind, sortedIndex) { |
645 return function(array, item, idx) { |
692 return function(array, item, idx) { |
646 var i = 0, length = getLength(array); |
693 var i = 0, length = getLength(array); |
647 if (typeof idx == 'number') { |
694 if (typeof idx == 'number') { |
648 if (dir > 0) { |
695 if (dir > 0) { |
649 i = idx >= 0 ? idx : Math.max(idx + length, i); |
696 i = idx >= 0 ? idx : Math.max(idx + length, i); |
650 } else { |
697 } else { |
651 length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1; |
698 length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1; |
652 } |
699 } |
653 } else if (sortedIndex && idx && length) { |
700 } else if (sortedIndex && idx && length) { |
654 idx = sortedIndex(array, item); |
701 idx = sortedIndex(array, item); |
655 return array[idx] === item ? idx : -1; |
702 return array[idx] === item ? idx : -1; |
656 } |
703 } |
690 } |
739 } |
691 |
740 |
692 return range; |
741 return range; |
693 }; |
742 }; |
694 |
743 |
|
744 // Chunk a single array into multiple arrays, each containing `count` or fewer |
|
745 // items. |
|
746 _.chunk = function(array, count) { |
|
747 if (count == null || count < 1) return []; |
|
748 var result = []; |
|
749 var i = 0, length = array.length; |
|
750 while (i < length) { |
|
751 result.push(slice.call(array, i, i += count)); |
|
752 } |
|
753 return result; |
|
754 }; |
|
755 |
695 // Function (ahem) Functions |
756 // Function (ahem) Functions |
696 // ------------------ |
757 // ------------------ |
697 |
758 |
698 // Determines whether to execute a function as a constructor |
759 // Determines whether to execute a function as a constructor |
699 // or a normal function with the provided arguments |
760 // or a normal function with the provided arguments. |
700 var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) { |
761 var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) { |
701 if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args); |
762 if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args); |
702 var self = baseCreate(sourceFunc.prototype); |
763 var self = baseCreate(sourceFunc.prototype); |
703 var result = sourceFunc.apply(self, args); |
764 var result = sourceFunc.apply(self, args); |
704 if (_.isObject(result)) return result; |
765 if (_.isObject(result)) return result; |
706 }; |
767 }; |
707 |
768 |
708 // Create a function bound to a given object (assigning `this`, and arguments, |
769 // Create a function bound to a given object (assigning `this`, and arguments, |
709 // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if |
770 // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if |
710 // available. |
771 // available. |
711 _.bind = function(func, context) { |
772 _.bind = restArguments(function(func, context, args) { |
712 if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); |
|
713 if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function'); |
773 if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function'); |
714 var args = slice.call(arguments, 2); |
774 var bound = restArguments(function(callArgs) { |
715 var bound = function() { |
775 return executeBound(func, bound, context, this, args.concat(callArgs)); |
716 return executeBound(func, bound, context, this, args.concat(slice.call(arguments))); |
776 }); |
717 }; |
|
718 return bound; |
777 return bound; |
719 }; |
778 }); |
720 |
779 |
721 // Partially apply a function by creating a version that has had some of its |
780 // Partially apply a function by creating a version that has had some of its |
722 // arguments pre-filled, without changing its dynamic `this` context. _ acts |
781 // arguments pre-filled, without changing its dynamic `this` context. _ acts |
723 // as a placeholder, allowing any combination of arguments to be pre-filled. |
782 // as a placeholder by default, allowing any combination of arguments to be |
724 _.partial = function(func) { |
783 // pre-filled. Set `_.partial.placeholder` for a custom placeholder argument. |
725 var boundArgs = slice.call(arguments, 1); |
784 _.partial = restArguments(function(func, boundArgs) { |
|
785 var placeholder = _.partial.placeholder; |
726 var bound = function() { |
786 var bound = function() { |
727 var position = 0, length = boundArgs.length; |
787 var position = 0, length = boundArgs.length; |
728 var args = Array(length); |
788 var args = Array(length); |
729 for (var i = 0; i < length; i++) { |
789 for (var i = 0; i < length; i++) { |
730 args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i]; |
790 args[i] = boundArgs[i] === placeholder ? arguments[position++] : boundArgs[i]; |
731 } |
791 } |
732 while (position < arguments.length) args.push(arguments[position++]); |
792 while (position < arguments.length) args.push(arguments[position++]); |
733 return executeBound(func, bound, this, this, args); |
793 return executeBound(func, bound, this, this, args); |
734 }; |
794 }; |
735 return bound; |
795 return bound; |
736 }; |
796 }); |
|
797 |
|
798 _.partial.placeholder = _; |
737 |
799 |
738 // Bind a number of an object's methods to that object. Remaining arguments |
800 // Bind a number of an object's methods to that object. Remaining arguments |
739 // are the method names to be bound. Useful for ensuring that all callbacks |
801 // are the method names to be bound. Useful for ensuring that all callbacks |
740 // defined on an object belong to it. |
802 // defined on an object belong to it. |
741 _.bindAll = function(obj) { |
803 _.bindAll = restArguments(function(obj, keys) { |
742 var i, length = arguments.length, key; |
804 keys = flatten(keys, false, false); |
743 if (length <= 1) throw new Error('bindAll must be passed function names'); |
805 var index = keys.length; |
744 for (i = 1; i < length; i++) { |
806 if (index < 1) throw new Error('bindAll must be passed function names'); |
745 key = arguments[i]; |
807 while (index--) { |
|
808 var key = keys[index]; |
746 obj[key] = _.bind(obj[key], obj); |
809 obj[key] = _.bind(obj[key], obj); |
747 } |
810 } |
748 return obj; |
811 }); |
749 }; |
|
750 |
812 |
751 // Memoize an expensive function by storing its results. |
813 // Memoize an expensive function by storing its results. |
752 _.memoize = function(func, hasher) { |
814 _.memoize = function(func, hasher) { |
753 var memoize = function(key) { |
815 var memoize = function(key) { |
754 var cache = memoize.cache; |
816 var cache = memoize.cache; |
755 var address = '' + (hasher ? hasher.apply(this, arguments) : key); |
817 var address = '' + (hasher ? hasher.apply(this, arguments) : key); |
756 if (!_.has(cache, address)) cache[address] = func.apply(this, arguments); |
818 if (!has(cache, address)) cache[address] = func.apply(this, arguments); |
757 return cache[address]; |
819 return cache[address]; |
758 }; |
820 }; |
759 memoize.cache = {}; |
821 memoize.cache = {}; |
760 return memoize; |
822 return memoize; |
761 }; |
823 }; |
762 |
824 |
763 // Delays a function for the given number of milliseconds, and then calls |
825 // Delays a function for the given number of milliseconds, and then calls |
764 // it with the arguments supplied. |
826 // it with the arguments supplied. |
765 _.delay = function(func, wait) { |
827 _.delay = restArguments(function(func, wait, args) { |
766 var args = slice.call(arguments, 2); |
828 return setTimeout(function() { |
767 return setTimeout(function(){ |
|
768 return func.apply(null, args); |
829 return func.apply(null, args); |
769 }, wait); |
830 }, wait); |
770 }; |
831 }); |
771 |
832 |
772 // Defers a function, scheduling it to run after the current call stack has |
833 // Defers a function, scheduling it to run after the current call stack has |
773 // cleared. |
834 // cleared. |
774 _.defer = _.partial(_.delay, _, 1); |
835 _.defer = _.partial(_.delay, _, 1); |
775 |
836 |
777 // during a given window of time. Normally, the throttled function will run |
838 // during a given window of time. Normally, the throttled function will run |
778 // as much as it can, without ever going more than once per `wait` duration; |
839 // as much as it can, without ever going more than once per `wait` duration; |
779 // but if you'd like to disable the execution on the leading edge, pass |
840 // but if you'd like to disable the execution on the leading edge, pass |
780 // `{leading: false}`. To disable execution on the trailing edge, ditto. |
841 // `{leading: false}`. To disable execution on the trailing edge, ditto. |
781 _.throttle = function(func, wait, options) { |
842 _.throttle = function(func, wait, options) { |
782 var context, args, result; |
843 var timeout, context, args, result; |
783 var timeout = null; |
|
784 var previous = 0; |
844 var previous = 0; |
785 if (!options) options = {}; |
845 if (!options) options = {}; |
|
846 |
786 var later = function() { |
847 var later = function() { |
787 previous = options.leading === false ? 0 : _.now(); |
848 previous = options.leading === false ? 0 : _.now(); |
788 timeout = null; |
849 timeout = null; |
789 result = func.apply(context, args); |
850 result = func.apply(context, args); |
790 if (!timeout) context = args = null; |
851 if (!timeout) context = args = null; |
791 }; |
852 }; |
792 return function() { |
853 |
|
854 var throttled = function() { |
793 var now = _.now(); |
855 var now = _.now(); |
794 if (!previous && options.leading === false) previous = now; |
856 if (!previous && options.leading === false) previous = now; |
795 var remaining = wait - (now - previous); |
857 var remaining = wait - (now - previous); |
796 context = this; |
858 context = this; |
797 args = arguments; |
859 args = arguments; |
806 } else if (!timeout && options.trailing !== false) { |
868 } else if (!timeout && options.trailing !== false) { |
807 timeout = setTimeout(later, remaining); |
869 timeout = setTimeout(later, remaining); |
808 } |
870 } |
809 return result; |
871 return result; |
810 }; |
872 }; |
|
873 |
|
874 throttled.cancel = function() { |
|
875 clearTimeout(timeout); |
|
876 previous = 0; |
|
877 timeout = context = args = null; |
|
878 }; |
|
879 |
|
880 return throttled; |
811 }; |
881 }; |
812 |
882 |
813 // Returns a function, that, as long as it continues to be invoked, will not |
883 // Returns a function, that, as long as it continues to be invoked, will not |
814 // be triggered. The function will be called after it stops being called for |
884 // be triggered. The function will be called after it stops being called for |
815 // N milliseconds. If `immediate` is passed, trigger the function on the |
885 // N milliseconds. If `immediate` is passed, trigger the function on the |
816 // leading edge, instead of the trailing. |
886 // leading edge, instead of the trailing. |
817 _.debounce = function(func, wait, immediate) { |
887 _.debounce = function(func, wait, immediate) { |
818 var timeout, args, context, timestamp, result; |
888 var timeout, result; |
819 |
889 |
820 var later = function() { |
890 var later = function(context, args) { |
821 var last = _.now() - timestamp; |
891 timeout = null; |
822 |
892 if (args) result = func.apply(context, args); |
823 if (last < wait && last >= 0) { |
893 }; |
824 timeout = setTimeout(later, wait - last); |
894 |
|
895 var debounced = restArguments(function(args) { |
|
896 if (timeout) clearTimeout(timeout); |
|
897 if (immediate) { |
|
898 var callNow = !timeout; |
|
899 timeout = setTimeout(later, wait); |
|
900 if (callNow) result = func.apply(this, args); |
825 } else { |
901 } else { |
826 timeout = null; |
902 timeout = _.delay(later, wait, this, args); |
827 if (!immediate) { |
|
828 result = func.apply(context, args); |
|
829 if (!timeout) context = args = null; |
|
830 } |
|
831 } |
|
832 }; |
|
833 |
|
834 return function() { |
|
835 context = this; |
|
836 args = arguments; |
|
837 timestamp = _.now(); |
|
838 var callNow = immediate && !timeout; |
|
839 if (!timeout) timeout = setTimeout(later, wait); |
|
840 if (callNow) { |
|
841 result = func.apply(context, args); |
|
842 context = args = null; |
|
843 } |
903 } |
844 |
904 |
845 return result; |
905 return result; |
846 }; |
906 }); |
|
907 |
|
908 debounced.cancel = function() { |
|
909 clearTimeout(timeout); |
|
910 timeout = null; |
|
911 }; |
|
912 |
|
913 return debounced; |
847 }; |
914 }; |
848 |
915 |
849 // Returns the first function passed as an argument to the second, |
916 // Returns the first function passed as an argument to the second, |
850 // allowing you to adjust arguments, run code before and after, and |
917 // allowing you to adjust arguments, run code before and after, and |
851 // conditionally execute the original function. |
918 // conditionally execute the original function. |
896 |
963 |
897 // Returns a function that will be executed at most one time, no matter how |
964 // Returns a function that will be executed at most one time, no matter how |
898 // often you call it. Useful for lazy initialization. |
965 // often you call it. Useful for lazy initialization. |
899 _.once = _.partial(_.before, 2); |
966 _.once = _.partial(_.before, 2); |
900 |
967 |
|
968 _.restArguments = restArguments; |
|
969 |
901 // Object Functions |
970 // Object Functions |
902 // ---------------- |
971 // ---------------- |
903 |
972 |
904 // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed. |
973 // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed. |
905 var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString'); |
974 var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString'); |
906 var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString', |
975 var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString', |
907 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString']; |
976 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString']; |
908 |
977 |
909 function collectNonEnumProps(obj, keys) { |
978 var collectNonEnumProps = function(obj, keys) { |
910 var nonEnumIdx = nonEnumerableProps.length; |
979 var nonEnumIdx = nonEnumerableProps.length; |
911 var constructor = obj.constructor; |
980 var constructor = obj.constructor; |
912 var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto; |
981 var proto = _.isFunction(constructor) && constructor.prototype || ObjProto; |
913 |
982 |
914 // Constructor is a special case. |
983 // Constructor is a special case. |
915 var prop = 'constructor'; |
984 var prop = 'constructor'; |
916 if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop); |
985 if (has(obj, prop) && !_.contains(keys, prop)) keys.push(prop); |
917 |
986 |
918 while (nonEnumIdx--) { |
987 while (nonEnumIdx--) { |
919 prop = nonEnumerableProps[nonEnumIdx]; |
988 prop = nonEnumerableProps[nonEnumIdx]; |
920 if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) { |
989 if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) { |
921 keys.push(prop); |
990 keys.push(prop); |
922 } |
991 } |
923 } |
992 } |
924 } |
993 }; |
925 |
994 |
926 // Retrieve the names of an object's own properties. |
995 // Retrieve the names of an object's own properties. |
927 // Delegates to **ECMAScript 5**'s native `Object.keys` |
996 // Delegates to **ECMAScript 5**'s native `Object.keys`. |
928 _.keys = function(obj) { |
997 _.keys = function(obj) { |
929 if (!_.isObject(obj)) return []; |
998 if (!_.isObject(obj)) return []; |
930 if (nativeKeys) return nativeKeys(obj); |
999 if (nativeKeys) return nativeKeys(obj); |
931 var keys = []; |
1000 var keys = []; |
932 for (var key in obj) if (_.has(obj, key)) keys.push(key); |
1001 for (var key in obj) if (has(obj, key)) keys.push(key); |
933 // Ahem, IE < 9. |
1002 // Ahem, IE < 9. |
934 if (hasEnumBug) collectNonEnumProps(obj, keys); |
1003 if (hasEnumBug) collectNonEnumProps(obj, keys); |
935 return keys; |
1004 return keys; |
936 }; |
1005 }; |
937 |
1006 |
954 values[i] = obj[keys[i]]; |
1023 values[i] = obj[keys[i]]; |
955 } |
1024 } |
956 return values; |
1025 return values; |
957 }; |
1026 }; |
958 |
1027 |
959 // Returns the results of applying the iteratee to each element of the object |
1028 // Returns the results of applying the iteratee to each element of the object. |
960 // In contrast to _.map it returns an object |
1029 // In contrast to _.map it returns an object. |
961 _.mapObject = function(obj, iteratee, context) { |
1030 _.mapObject = function(obj, iteratee, context) { |
962 iteratee = cb(iteratee, context); |
1031 iteratee = cb(iteratee, context); |
963 var keys = _.keys(obj), |
1032 var keys = _.keys(obj), |
964 length = keys.length, |
1033 length = keys.length, |
965 results = {}, |
1034 results = {}; |
966 currentKey; |
1035 for (var index = 0; index < length; index++) { |
967 for (var index = 0; index < length; index++) { |
1036 var currentKey = keys[index]; |
968 currentKey = keys[index]; |
1037 results[currentKey] = iteratee(obj[currentKey], currentKey, obj); |
969 results[currentKey] = iteratee(obj[currentKey], currentKey, obj); |
1038 } |
970 } |
1039 return results; |
971 return results; |
|
972 }; |
1040 }; |
973 |
1041 |
974 // Convert an object into a list of `[key, value]` pairs. |
1042 // Convert an object into a list of `[key, value]` pairs. |
|
1043 // The opposite of _.object. |
975 _.pairs = function(obj) { |
1044 _.pairs = function(obj) { |
976 var keys = _.keys(obj); |
1045 var keys = _.keys(obj); |
977 var length = keys.length; |
1046 var length = keys.length; |
978 var pairs = Array(length); |
1047 var pairs = Array(length); |
979 for (var i = 0; i < length; i++) { |
1048 for (var i = 0; i < length; i++) { |
991 } |
1060 } |
992 return result; |
1061 return result; |
993 }; |
1062 }; |
994 |
1063 |
995 // Return a sorted list of the function names available on the object. |
1064 // Return a sorted list of the function names available on the object. |
996 // Aliased as `methods` |
1065 // Aliased as `methods`. |
997 _.functions = _.methods = function(obj) { |
1066 _.functions = _.methods = function(obj) { |
998 var names = []; |
1067 var names = []; |
999 for (var key in obj) { |
1068 for (var key in obj) { |
1000 if (_.isFunction(obj[key])) names.push(key); |
1069 if (_.isFunction(obj[key])) names.push(key); |
1001 } |
1070 } |
1002 return names.sort(); |
1071 return names.sort(); |
1003 }; |
1072 }; |
1004 |
1073 |
|
1074 // An internal function for creating assigner functions. |
|
1075 var createAssigner = function(keysFunc, defaults) { |
|
1076 return function(obj) { |
|
1077 var length = arguments.length; |
|
1078 if (defaults) obj = Object(obj); |
|
1079 if (length < 2 || obj == null) return obj; |
|
1080 for (var index = 1; index < length; index++) { |
|
1081 var source = arguments[index], |
|
1082 keys = keysFunc(source), |
|
1083 l = keys.length; |
|
1084 for (var i = 0; i < l; i++) { |
|
1085 var key = keys[i]; |
|
1086 if (!defaults || obj[key] === void 0) obj[key] = source[key]; |
|
1087 } |
|
1088 } |
|
1089 return obj; |
|
1090 }; |
|
1091 }; |
|
1092 |
1005 // Extend a given object with all the properties in passed-in object(s). |
1093 // Extend a given object with all the properties in passed-in object(s). |
1006 _.extend = createAssigner(_.allKeys); |
1094 _.extend = createAssigner(_.allKeys); |
1007 |
1095 |
1008 // Assigns a given object with all the own properties in the passed-in object(s) |
1096 // Assigns a given object with all the own properties in the passed-in object(s). |
1009 // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) |
1097 // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) |
1010 _.extendOwn = _.assign = createAssigner(_.keys); |
1098 _.extendOwn = _.assign = createAssigner(_.keys); |
1011 |
1099 |
1012 // Returns the first key on an object that passes a predicate test |
1100 // Returns the first key on an object that passes a predicate test. |
1013 _.findKey = function(obj, predicate, context) { |
1101 _.findKey = function(obj, predicate, context) { |
1014 predicate = cb(predicate, context); |
1102 predicate = cb(predicate, context); |
1015 var keys = _.keys(obj), key; |
1103 var keys = _.keys(obj), key; |
1016 for (var i = 0, length = keys.length; i < length; i++) { |
1104 for (var i = 0, length = keys.length; i < length; i++) { |
1017 key = keys[i]; |
1105 key = keys[i]; |
1018 if (predicate(obj[key], key, obj)) return key; |
1106 if (predicate(obj[key], key, obj)) return key; |
1019 } |
1107 } |
1020 }; |
1108 }; |
1021 |
1109 |
|
1110 // Internal pick helper function to determine if `obj` has key `key`. |
|
1111 var keyInObj = function(value, key, obj) { |
|
1112 return key in obj; |
|
1113 }; |
|
1114 |
1022 // Return a copy of the object only containing the whitelisted properties. |
1115 // Return a copy of the object only containing the whitelisted properties. |
1023 _.pick = function(object, oiteratee, context) { |
1116 _.pick = restArguments(function(obj, keys) { |
1024 var result = {}, obj = object, iteratee, keys; |
1117 var result = {}, iteratee = keys[0]; |
1025 if (obj == null) return result; |
1118 if (obj == null) return result; |
1026 if (_.isFunction(oiteratee)) { |
1119 if (_.isFunction(iteratee)) { |
|
1120 if (keys.length > 1) iteratee = optimizeCb(iteratee, keys[1]); |
1027 keys = _.allKeys(obj); |
1121 keys = _.allKeys(obj); |
1028 iteratee = optimizeCb(oiteratee, context); |
|
1029 } else { |
1122 } else { |
1030 keys = flatten(arguments, false, false, 1); |
1123 iteratee = keyInObj; |
1031 iteratee = function(value, key, obj) { return key in obj; }; |
1124 keys = flatten(keys, false, false); |
1032 obj = Object(obj); |
1125 obj = Object(obj); |
1033 } |
1126 } |
1034 for (var i = 0, length = keys.length; i < length; i++) { |
1127 for (var i = 0, length = keys.length; i < length; i++) { |
1035 var key = keys[i]; |
1128 var key = keys[i]; |
1036 var value = obj[key]; |
1129 var value = obj[key]; |
1037 if (iteratee(value, key, obj)) result[key] = value; |
1130 if (iteratee(value, key, obj)) result[key] = value; |
1038 } |
1131 } |
1039 return result; |
1132 return result; |
1040 }; |
1133 }); |
1041 |
1134 |
1042 // Return a copy of the object without the blacklisted properties. |
1135 // Return a copy of the object without the blacklisted properties. |
1043 _.omit = function(obj, iteratee, context) { |
1136 _.omit = restArguments(function(obj, keys) { |
|
1137 var iteratee = keys[0], context; |
1044 if (_.isFunction(iteratee)) { |
1138 if (_.isFunction(iteratee)) { |
1045 iteratee = _.negate(iteratee); |
1139 iteratee = _.negate(iteratee); |
|
1140 if (keys.length > 1) context = keys[1]; |
1046 } else { |
1141 } else { |
1047 var keys = _.map(flatten(arguments, false, false, 1), String); |
1142 keys = _.map(flatten(keys, false, false), String); |
1048 iteratee = function(value, key) { |
1143 iteratee = function(value, key) { |
1049 return !_.contains(keys, key); |
1144 return !_.contains(keys, key); |
1050 }; |
1145 }; |
1051 } |
1146 } |
1052 return _.pick(obj, iteratee, context); |
1147 return _.pick(obj, iteratee, context); |
1053 }; |
1148 }); |
1054 |
1149 |
1055 // Fill in a given object with default properties. |
1150 // Fill in a given object with default properties. |
1056 _.defaults = createAssigner(_.allKeys, true); |
1151 _.defaults = createAssigner(_.allKeys, true); |
1057 |
1152 |
1058 // Creates an object that inherits from the given prototype object. |
1153 // Creates an object that inherits from the given prototype object. |
1090 return true; |
1185 return true; |
1091 }; |
1186 }; |
1092 |
1187 |
1093 |
1188 |
1094 // Internal recursive comparison function for `isEqual`. |
1189 // Internal recursive comparison function for `isEqual`. |
1095 var eq = function(a, b, aStack, bStack) { |
1190 var eq, deepEq; |
|
1191 eq = function(a, b, aStack, bStack) { |
1096 // Identical objects are equal. `0 === -0`, but they aren't identical. |
1192 // Identical objects are equal. `0 === -0`, but they aren't identical. |
1097 // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). |
1193 // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). |
1098 if (a === b) return a !== 0 || 1 / a === 1 / b; |
1194 if (a === b) return a !== 0 || 1 / a === 1 / b; |
1099 // A strict comparison is necessary because `null == undefined`. |
1195 // `null` or `undefined` only equal to itself (strict comparison). |
1100 if (a == null || b == null) return a === b; |
1196 if (a == null || b == null) return false; |
|
1197 // `NaN`s are equivalent, but non-reflexive. |
|
1198 if (a !== a) return b !== b; |
|
1199 // Exhaust primitive checks |
|
1200 var type = typeof a; |
|
1201 if (type !== 'function' && type !== 'object' && typeof b != 'object') return false; |
|
1202 return deepEq(a, b, aStack, bStack); |
|
1203 }; |
|
1204 |
|
1205 // Internal recursive comparison function for `isEqual`. |
|
1206 deepEq = function(a, b, aStack, bStack) { |
1101 // Unwrap any wrapped objects. |
1207 // Unwrap any wrapped objects. |
1102 if (a instanceof _) a = a._wrapped; |
1208 if (a instanceof _) a = a._wrapped; |
1103 if (b instanceof _) b = b._wrapped; |
1209 if (b instanceof _) b = b._wrapped; |
1104 // Compare `[[Class]]` names. |
1210 // Compare `[[Class]]` names. |
1105 var className = toString.call(a); |
1211 var className = toString.call(a); |
1112 // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is |
1218 // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is |
1113 // equivalent to `new String("5")`. |
1219 // equivalent to `new String("5")`. |
1114 return '' + a === '' + b; |
1220 return '' + a === '' + b; |
1115 case '[object Number]': |
1221 case '[object Number]': |
1116 // `NaN`s are equivalent, but non-reflexive. |
1222 // `NaN`s are equivalent, but non-reflexive. |
1117 // Object(NaN) is equivalent to NaN |
1223 // Object(NaN) is equivalent to NaN. |
1118 if (+a !== +a) return +b !== +b; |
1224 if (+a !== +a) return +b !== +b; |
1119 // An `egal` comparison is performed for other numeric values. |
1225 // An `egal` comparison is performed for other numeric values. |
1120 return +a === 0 ? 1 / +a === 1 / b : +a === +b; |
1226 return +a === 0 ? 1 / +a === 1 / b : +a === +b; |
1121 case '[object Date]': |
1227 case '[object Date]': |
1122 case '[object Boolean]': |
1228 case '[object Boolean]': |
1123 // Coerce dates and booleans to numeric primitive values. Dates are compared by their |
1229 // Coerce dates and booleans to numeric primitive values. Dates are compared by their |
1124 // millisecond representations. Note that invalid dates with millisecond representations |
1230 // millisecond representations. Note that invalid dates with millisecond representations |
1125 // of `NaN` are not equivalent. |
1231 // of `NaN` are not equivalent. |
1126 return +a === +b; |
1232 return +a === +b; |
|
1233 case '[object Symbol]': |
|
1234 return SymbolProto.valueOf.call(a) === SymbolProto.valueOf.call(b); |
1127 } |
1235 } |
1128 |
1236 |
1129 var areArrays = className === '[object Array]'; |
1237 var areArrays = className === '[object Array]'; |
1130 if (!areArrays) { |
1238 if (!areArrays) { |
1131 if (typeof a != 'object' || typeof b != 'object') return false; |
1239 if (typeof a != 'object' || typeof b != 'object') return false; |
1212 _.isObject = function(obj) { |
1320 _.isObject = function(obj) { |
1213 var type = typeof obj; |
1321 var type = typeof obj; |
1214 return type === 'function' || type === 'object' && !!obj; |
1322 return type === 'function' || type === 'object' && !!obj; |
1215 }; |
1323 }; |
1216 |
1324 |
1217 // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError. |
1325 // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError, isMap, isWeakMap, isSet, isWeakSet. |
1218 _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) { |
1326 _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error', 'Symbol', 'Map', 'WeakMap', 'Set', 'WeakSet'], function(name) { |
1219 _['is' + name] = function(obj) { |
1327 _['is' + name] = function(obj) { |
1220 return toString.call(obj) === '[object ' + name + ']'; |
1328 return toString.call(obj) === '[object ' + name + ']'; |
1221 }; |
1329 }; |
1222 }); |
1330 }); |
1223 |
1331 |
1224 // Define a fallback version of the method in browsers (ahem, IE < 9), where |
1332 // Define a fallback version of the method in browsers (ahem, IE < 9), where |
1225 // there isn't any inspectable "Arguments" type. |
1333 // there isn't any inspectable "Arguments" type. |
1226 if (!_.isArguments(arguments)) { |
1334 if (!_.isArguments(arguments)) { |
1227 _.isArguments = function(obj) { |
1335 _.isArguments = function(obj) { |
1228 return _.has(obj, 'callee'); |
1336 return has(obj, 'callee'); |
1229 }; |
1337 }; |
1230 } |
1338 } |
1231 |
1339 |
1232 // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8, |
1340 // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8, |
1233 // IE 11 (#1621), and in Safari 8 (#1929). |
1341 // IE 11 (#1621), Safari 8 (#1929), and PhantomJS (#2236). |
1234 if (typeof /./ != 'function' && typeof Int8Array != 'object') { |
1342 var nodelist = root.document && root.document.childNodes; |
|
1343 if (typeof /./ != 'function' && typeof Int8Array != 'object' && typeof nodelist != 'function') { |
1235 _.isFunction = function(obj) { |
1344 _.isFunction = function(obj) { |
1236 return typeof obj == 'function' || false; |
1345 return typeof obj == 'function' || false; |
1237 }; |
1346 }; |
1238 } |
1347 } |
1239 |
1348 |
1240 // Is a given object a finite number? |
1349 // Is a given object a finite number? |
1241 _.isFinite = function(obj) { |
1350 _.isFinite = function(obj) { |
1242 return isFinite(obj) && !isNaN(parseFloat(obj)); |
1351 return !_.isSymbol(obj) && isFinite(obj) && !isNaN(parseFloat(obj)); |
1243 }; |
1352 }; |
1244 |
1353 |
1245 // Is the given value `NaN`? (NaN is the only number which does not equal itself). |
1354 // Is the given value `NaN`? |
1246 _.isNaN = function(obj) { |
1355 _.isNaN = function(obj) { |
1247 return _.isNumber(obj) && obj !== +obj; |
1356 return _.isNumber(obj) && isNaN(obj); |
1248 }; |
1357 }; |
1249 |
1358 |
1250 // Is a given value a boolean? |
1359 // Is a given value a boolean? |
1251 _.isBoolean = function(obj) { |
1360 _.isBoolean = function(obj) { |
1252 return obj === true || obj === false || toString.call(obj) === '[object Boolean]'; |
1361 return obj === true || obj === false || toString.call(obj) === '[object Boolean]'; |
1358 }; |
1490 }; |
1359 }; |
1491 }; |
1360 _.escape = createEscaper(escapeMap); |
1492 _.escape = createEscaper(escapeMap); |
1361 _.unescape = createEscaper(unescapeMap); |
1493 _.unescape = createEscaper(unescapeMap); |
1362 |
1494 |
1363 // If the value of the named `property` is a function then invoke it with the |
1495 // Traverses the children of `obj` along `path`. If a child is a function, it |
1364 // `object` as context; otherwise, return it. |
1496 // is invoked with its parent as context. Returns the value of the final |
1365 _.result = function(object, property, fallback) { |
1497 // child, or `fallback` if any child is undefined. |
1366 var value = object == null ? void 0 : object[property]; |
1498 _.result = function(obj, path, fallback) { |
1367 if (value === void 0) { |
1499 if (!_.isArray(path)) path = [path]; |
1368 value = fallback; |
1500 var length = path.length; |
1369 } |
1501 if (!length) { |
1370 return _.isFunction(value) ? value.call(object) : value; |
1502 return _.isFunction(fallback) ? fallback.call(obj) : fallback; |
|
1503 } |
|
1504 for (var i = 0; i < length; i++) { |
|
1505 var prop = obj == null ? void 0 : obj[path[i]]; |
|
1506 if (prop === void 0) { |
|
1507 prop = fallback; |
|
1508 i = length; // Ensure we don't continue iterating. |
|
1509 } |
|
1510 obj = _.isFunction(prop) ? prop.call(obj) : prop; |
|
1511 } |
|
1512 return obj; |
1371 }; |
1513 }; |
1372 |
1514 |
1373 // Generate a unique integer id (unique within the entire client session). |
1515 // Generate a unique integer id (unique within the entire client session). |
1374 // Useful for temporary DOM ids. |
1516 // Useful for temporary DOM ids. |
1375 var idCounter = 0; |
1517 var idCounter = 0; |
1379 }; |
1521 }; |
1380 |
1522 |
1381 // By default, Underscore uses ERB-style template delimiters, change the |
1523 // By default, Underscore uses ERB-style template delimiters, change the |
1382 // following template settings to use alternative delimiters. |
1524 // following template settings to use alternative delimiters. |
1383 _.templateSettings = { |
1525 _.templateSettings = { |
1384 evaluate : /<%([\s\S]+?)%>/g, |
1526 evaluate: /<%([\s\S]+?)%>/g, |
1385 interpolate : /<%=([\s\S]+?)%>/g, |
1527 interpolate: /<%=([\s\S]+?)%>/g, |
1386 escape : /<%-([\s\S]+?)%>/g |
1528 escape: /<%-([\s\S]+?)%>/g |
1387 }; |
1529 }; |
1388 |
1530 |
1389 // When customizing `templateSettings`, if you don't want to define an |
1531 // When customizing `templateSettings`, if you don't want to define an |
1390 // interpolation, evaluation or escaping regex, we need one that is |
1532 // interpolation, evaluation or escaping regex, we need one that is |
1391 // guaranteed not to match. |
1533 // guaranteed not to match. |
1392 var noMatch = /(.)^/; |
1534 var noMatch = /(.)^/; |
1393 |
1535 |
1394 // Certain characters need to be escaped so that they can be put into a |
1536 // Certain characters need to be escaped so that they can be put into a |
1395 // string literal. |
1537 // string literal. |
1396 var escapes = { |
1538 var escapes = { |
1397 "'": "'", |
1539 "'": "'", |
1398 '\\': '\\', |
1540 '\\': '\\', |
1399 '\r': 'r', |
1541 '\r': 'r', |
1400 '\n': 'n', |
1542 '\n': 'n', |
1401 '\u2028': 'u2028', |
1543 '\u2028': 'u2028', |
1402 '\u2029': 'u2029' |
1544 '\u2029': 'u2029' |
1403 }; |
1545 }; |
1404 |
1546 |
1405 var escaper = /\\|'|\r|\n|\u2028|\u2029/g; |
1547 var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g; |
1406 |
1548 |
1407 var escapeChar = function(match) { |
1549 var escapeChar = function(match) { |
1408 return '\\' + escapes[match]; |
1550 return '\\' + escapes[match]; |
1409 }; |
1551 }; |
1410 |
1552 |
1425 |
1567 |
1426 // Compile the template source, escaping string literals appropriately. |
1568 // Compile the template source, escaping string literals appropriately. |
1427 var index = 0; |
1569 var index = 0; |
1428 var source = "__p+='"; |
1570 var source = "__p+='"; |
1429 text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { |
1571 text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { |
1430 source += text.slice(index, offset).replace(escaper, escapeChar); |
1572 source += text.slice(index, offset).replace(escapeRegExp, escapeChar); |
1431 index = offset + match.length; |
1573 index = offset + match.length; |
1432 |
1574 |
1433 if (escape) { |
1575 if (escape) { |
1434 source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; |
1576 source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; |
1435 } else if (interpolate) { |
1577 } else if (interpolate) { |
1436 source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; |
1578 source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; |
1437 } else if (evaluate) { |
1579 } else if (evaluate) { |
1438 source += "';\n" + evaluate + "\n__p+='"; |
1580 source += "';\n" + evaluate + "\n__p+='"; |
1439 } |
1581 } |
1440 |
1582 |
1441 // Adobe VMs need the match returned to produce the correct offest. |
1583 // Adobe VMs need the match returned to produce the correct offset. |
1442 return match; |
1584 return match; |
1443 }); |
1585 }); |
1444 source += "';\n"; |
1586 source += "';\n"; |
1445 |
1587 |
1446 // If a variable is not specified, place data values in local scope. |
1588 // If a variable is not specified, place data values in local scope. |
1480 // If Underscore is called as a function, it returns a wrapped object that |
1623 // If Underscore is called as a function, it returns a wrapped object that |
1481 // can be used OO-style. This wrapper holds altered versions of all the |
1624 // can be used OO-style. This wrapper holds altered versions of all the |
1482 // underscore functions. Wrapped objects may be chained. |
1625 // underscore functions. Wrapped objects may be chained. |
1483 |
1626 |
1484 // Helper function to continue chaining intermediate results. |
1627 // Helper function to continue chaining intermediate results. |
1485 var result = function(instance, obj) { |
1628 var chainResult = function(instance, obj) { |
1486 return instance._chain ? _(obj).chain() : obj; |
1629 return instance._chain ? _(obj).chain() : obj; |
1487 }; |
1630 }; |
1488 |
1631 |
1489 // Add your own custom functions to the Underscore object. |
1632 // Add your own custom functions to the Underscore object. |
1490 _.mixin = function(obj) { |
1633 _.mixin = function(obj) { |
1491 _.each(_.functions(obj), function(name) { |
1634 _.each(_.functions(obj), function(name) { |
1492 var func = _[name] = obj[name]; |
1635 var func = _[name] = obj[name]; |
1493 _.prototype[name] = function() { |
1636 _.prototype[name] = function() { |
1494 var args = [this._wrapped]; |
1637 var args = [this._wrapped]; |
1495 push.apply(args, arguments); |
1638 push.apply(args, arguments); |
1496 return result(this, func.apply(_, args)); |
1639 return chainResult(this, func.apply(_, args)); |
1497 }; |
1640 }; |
1498 }); |
1641 }); |
|
1642 return _; |
1499 }; |
1643 }; |
1500 |
1644 |
1501 // Add all of the Underscore functions to the wrapper object. |
1645 // Add all of the Underscore functions to the wrapper object. |
1502 _.mixin(_); |
1646 _.mixin(_); |
1503 |
1647 |
1506 var method = ArrayProto[name]; |
1650 var method = ArrayProto[name]; |
1507 _.prototype[name] = function() { |
1651 _.prototype[name] = function() { |
1508 var obj = this._wrapped; |
1652 var obj = this._wrapped; |
1509 method.apply(obj, arguments); |
1653 method.apply(obj, arguments); |
1510 if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0]; |
1654 if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0]; |
1511 return result(this, obj); |
1655 return chainResult(this, obj); |
1512 }; |
1656 }; |
1513 }); |
1657 }); |
1514 |
1658 |
1515 // Add all accessor Array functions to the wrapper. |
1659 // Add all accessor Array functions to the wrapper. |
1516 _.each(['concat', 'join', 'slice'], function(name) { |
1660 _.each(['concat', 'join', 'slice'], function(name) { |
1517 var method = ArrayProto[name]; |
1661 var method = ArrayProto[name]; |
1518 _.prototype[name] = function() { |
1662 _.prototype[name] = function() { |
1519 return result(this, method.apply(this._wrapped, arguments)); |
1663 return chainResult(this, method.apply(this._wrapped, arguments)); |
1520 }; |
1664 }; |
1521 }); |
1665 }); |
1522 |
1666 |
1523 // Extracts the result from a wrapped and chained object. |
1667 // Extracts the result from a wrapped and chained object. |
1524 _.prototype.value = function() { |
1668 _.prototype.value = function() { |
1528 // Provide unwrapping proxy for some methods used in engine operations |
1672 // Provide unwrapping proxy for some methods used in engine operations |
1529 // such as arithmetic and JSON stringification. |
1673 // such as arithmetic and JSON stringification. |
1530 _.prototype.valueOf = _.prototype.toJSON = _.prototype.value; |
1674 _.prototype.valueOf = _.prototype.toJSON = _.prototype.value; |
1531 |
1675 |
1532 _.prototype.toString = function() { |
1676 _.prototype.toString = function() { |
1533 return '' + this._wrapped; |
1677 return String(this._wrapped); |
1534 }; |
1678 }; |
1535 |
1679 |
1536 // AMD registration happens at the end for compatibility with AMD loaders |
1680 // AMD registration happens at the end for compatibility with AMD loaders |
1537 // that may not enforce next-turn semantics on modules. Even though general |
1681 // that may not enforce next-turn semantics on modules. Even though general |
1538 // practice for AMD registration is to be anonymous, underscore registers |
1682 // practice for AMD registration is to be anonymous, underscore registers |
1539 // as a named module because, like jQuery, it is a base library that is |
1683 // as a named module because, like jQuery, it is a base library that is |
1540 // popular enough to be bundled in a third party lib, but not be part of |
1684 // popular enough to be bundled in a third party lib, but not be part of |
1541 // an AMD load request. Those cases could generate an error when an |
1685 // an AMD load request. Those cases could generate an error when an |
1542 // anonymous define() is called outside of a loader request. |
1686 // anonymous define() is called outside of a loader request. |
1543 if (typeof define === 'function' && define.amd) { |
1687 if (typeof define == 'function' && define.amd) { |
1544 define('underscore', [], function() { |
1688 define('underscore', [], function() { |
1545 return _; |
1689 return _; |
1546 }); |
1690 }); |
1547 } |
1691 } |
1548 }.call(this)); |
1692 }()); |