1// Underscore.js 1.8.3 2// http://underscorejs.org 3// (c) 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors 4// Underscore may be freely distributed under the MIT license. 5 6(function() { 7 8 // Baseline setup 9 // -------------- 10 11 // Establish the root object, `window` (`self`) in the browser, `global` 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 18 // Save the previous value of the `_` variable. 19 var previousUnderscore = root._; 20 21 // Save bytes in the minified (but not gzipped) version: 22 var ArrayProto = Array.prototype, ObjProto = Object.prototype; 23 var SymbolProto = typeof Symbol !== 'undefined' ? Symbol.prototype : null; 24 25 // Create quick reference variables for speed access to core prototypes. 26 var push = ArrayProto.push, 27 slice = ArrayProto.slice, 28 toString = ObjProto.toString, 29 hasOwnProperty = ObjProto.hasOwnProperty; 30 31 // All **ECMAScript 5** native function implementations that we hope to use 32 // are declared here. 33 var nativeIsArray = Array.isArray, 34 nativeKeys = Object.keys, 35 nativeCreate = Object.create; 36 37 // Naked function reference for surrogate-prototype-swapping. 38 var Ctor = function(){}; 39 40 // Create a safe reference to the Underscore object for use below. 41 var _ = function(obj) { 42 if (obj instanceof _) return obj; 43 if (!(this instanceof _)) return new _(obj); 44 this._wrapped = obj; 45 }; 46 47 // Export the Underscore object for **Node.js**, with 48 // backwards-compatibility for their old module API. If we're in 49 // the browser, add `_` as a global object. 50 // (`nodeType` is checked to ensure that `module` 51 // and `exports` are not HTML elements.) 52 if (typeof exports != 'undefined' && !exports.nodeType) { 53 if (typeof module != 'undefined' && !module.nodeType && module.exports) { 54 exports = module.exports = _; 55 } 56 exports._ = _; 57 } else { 58 root._ = _; 59 } 60 61 // Current version. 62 _.VERSION = '1.8.3'; 63 64 // Internal function that returns an efficient (for current engines) version 65 // of the passed-in callback, to be repeatedly applied in other Underscore 66 // functions. 67 var optimizeCb = function(func, context, argCount) { 68 if (context === void 0) return func; 69 switch (argCount == null ? 3 : argCount) { 70 case 1: return function(value) { 71 return func.call(context, value); 72 }; 73 // The 2-parameter case has been omitted only because no current consumers 74 // made use of it. 75 case 3: return function(value, index, collection) { 76 return func.call(context, value, index, collection); 77 }; 78 case 4: return function(accumulator, value, index, collection) { 79 return func.call(context, accumulator, value, index, collection); 80 }; 81 } 82 return function() { 83 return func.apply(context, arguments); 84 }; 85 }; 86 87 var builtinIteratee; 88 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. 92 var cb = function(value, context, argCount) { 93 if (_.iteratee !== builtinIteratee) return _.iteratee(value, context); 94 if (value == null) return _.identity; 95 if (_.isFunction(value)) return optimizeCb(value, context, argCount); 96 if (_.isObject(value)) return _.matcher(value); 97 return _.property(value); 98 }; 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) { 104 return cb(value, context, Infinity); 105 }; 106 107 // Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html) 108 // This accumulates the arguments passed into an array, after a given index. 109 var restArgs = function(func, startIndex) { 110 startIndex = startIndex == null ? func.length - 1 : +startIndex; 111 return function() { 112 var length = Math.max(arguments.length - startIndex, 0); 113 var rest = Array(length); 114 for (var index = 0; index < length; index++) { 115 rest[index] = arguments[index + startIndex]; 116 } 117 switch (startIndex) { 118 case 0: return func.call(this, rest); 119 case 1: return func.call(this, arguments[0], rest); 120 case 2: return func.call(this, arguments[0], arguments[1], rest); 121 } 122 var args = Array(startIndex + 1); 123 for (index = 0; index < startIndex; index++) { 124 args[index] = arguments[index]; 125 } 126 args[startIndex] = rest; 127 return func.apply(this, args); 128 }; 129 }; 130 131 // An internal function for creating a new object that inherits from another. 132 var baseCreate = function(prototype) { 133 if (!_.isObject(prototype)) return {}; 134 if (nativeCreate) return nativeCreate(prototype); 135 Ctor.prototype = prototype; 136 var result = new Ctor; 137 Ctor.prototype = null; 138 return result; 139 }; 140 141 var property = function(key) { 142 return function(obj) { 143 return obj == null ? void 0 : obj[key]; 144 }; 145 }; 146 147 // Helper for collection methods to determine whether a collection 148 // should be iterated as an array or as an object. 149 // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength 150 // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094 151 var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1; 152 var getLength = property('length'); 153 var isArrayLike = function(collection) { 154 var length = getLength(collection); 155 return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX; 156 }; 157 158 // Collection Functions 159 // -------------------- 160 161 // The cornerstone, an `each` implementation, aka `forEach`. 162 // Handles raw objects in addition to array-likes. Treats all 163 // sparse array-likes as if they were dense. 164 _.each = _.forEach = function(obj, iteratee, context) { 165 iteratee = optimizeCb(iteratee, context); 166 var i, length; 167 if (isArrayLike(obj)) { 168 for (i = 0, length = obj.length; i < length; i++) { 169 iteratee(obj[i], i, obj); 170 } 171 } else { 172 var keys = _.keys(obj); 173 for (i = 0, length = keys.length; i < length; i++) { 174 iteratee(obj[keys[i]], keys[i], obj); 175 } 176 } 177 return obj; 178 }; 179 180 // Return the results of applying the iteratee to each element. 181 _.map = _.collect = function(obj, iteratee, context) { 182 iteratee = cb(iteratee, context); 183 var keys = !isArrayLike(obj) && _.keys(obj), 184 length = (keys || obj).length, 185 results = Array(length); 186 for (var index = 0; index < length; index++) { 187 var currentKey = keys ? keys[index] : index; 188 results[index] = iteratee(obj[currentKey], currentKey, obj); 189 } 190 return results; 191 }; 192 193 // Create a reducing function iterating left or right. 194 var createReduce = function(dir) { 195 // Wrap code that reassigns argument variables in a separate function than 196 // the one that accesses `arguments.length` to avoid a perf hit. (#1991) 197 var reducer = function(obj, iteratee, memo, initial) { 198 var keys = !isArrayLike(obj) && _.keys(obj), 199 length = (keys || obj).length, 200 index = dir > 0 ? 0 : length - 1; 201 if (!initial) { 202 memo = obj[keys ? keys[index] : index]; 203 index += dir; 204 } 205 for (; index >= 0 && index < length; index += dir) { 206 var currentKey = keys ? keys[index] : index; 207 memo = iteratee(memo, obj[currentKey], currentKey, obj); 208 } 209 return memo; 210 }; 211 212 return function(obj, iteratee, memo, context) { 213 var initial = arguments.length >= 3; 214 return reducer(obj, optimizeCb(iteratee, context, 4), memo, initial); 215 }; 216 }; 217 218 // **Reduce** builds up a single result from a list of values, aka `inject`, 219 // or `foldl`. 220 _.reduce = _.foldl = _.inject = createReduce(1); 221 222 // The right-associative version of reduce, also known as `foldr`. 223 _.reduceRight = _.foldr = createReduce(-1); 224 225 // Return the first value which passes a truth test. Aliased as `detect`. 226 _.find = _.detect = function(obj, predicate, context) { 227 var keyFinder = isArrayLike(obj) ? _.findIndex : _.findKey; 228 var key = keyFinder(obj, predicate, context); 229 if (key !== void 0 && key !== -1) return obj[key]; 230 }; 231 232 // Return all the elements that pass a truth test. 233 // Aliased as `select`. 234 _.filter = _.select = function(obj, predicate, context) { 235 var results = []; 236 predicate = cb(predicate, context); 237 _.each(obj, function(value, index, list) { 238 if (predicate(value, index, list)) results.push(value); 239 }); 240 return results; 241 }; 242 243 // Return all the elements for which a truth test fails. 244 _.reject = function(obj, predicate, context) { 245 return _.filter(obj, _.negate(cb(predicate)), context); 246 }; 247 248 // Determine whether all of the elements match a truth test. 249 // Aliased as `all`. 250 _.every = _.all = function(obj, predicate, context) { 251 predicate = cb(predicate, context); 252 var keys = !isArrayLike(obj) && _.keys(obj), 253 length = (keys || obj).length; 254 for (var index = 0; index < length; index++) { 255 var currentKey = keys ? keys[index] : index; 256 if (!predicate(obj[currentKey], currentKey, obj)) return false; 257 } 258 return true; 259 }; 260 261 // Determine if at least one element in the object matches a truth test. 262 // Aliased as `any`. 263 _.some = _.any = function(obj, predicate, context) { 264 predicate = cb(predicate, context); 265 var keys = !isArrayLike(obj) && _.keys(obj), 266 length = (keys || obj).length; 267 for (var index = 0; index < length; index++) { 268 var currentKey = keys ? keys[index] : index; 269 if (predicate(obj[currentKey], currentKey, obj)) return true; 270 } 271 return false; 272 }; 273 274 // Determine if the array or object contains a given item (using `===`). 275 // Aliased as `includes` and `include`. 276 _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) { 277 if (!isArrayLike(obj)) obj = _.values(obj); 278 if (typeof fromIndex != 'number' || guard) fromIndex = 0; 279 return _.indexOf(obj, item, fromIndex) >= 0; 280 }; 281 282 // Invoke a method (with arguments) on every item in a collection. 283 _.invoke = restArgs(function(obj, method, args) { 284 var isFunc = _.isFunction(method); 285 return _.map(obj, function(value) { 286 var func = isFunc ? method : value[method]; 287 return func == null ? func : func.apply(value, args); 288 }); 289 }); 290 291 // Convenience version of a common use case of `map`: fetching a property. 292 _.pluck = function(obj, key) { 293 return _.map(obj, _.property(key)); 294 }; 295 296 // Convenience version of a common use case of `filter`: selecting only objects 297 // containing specific `key:value` pairs. 298 _.where = function(obj, attrs) { 299 return _.filter(obj, _.matcher(attrs)); 300 }; 301 302 // Convenience version of a common use case of `find`: getting the first object 303 // containing specific `key:value` pairs. 304 _.findWhere = function(obj, attrs) { 305 return _.find(obj, _.matcher(attrs)); 306 }; 307 308 // Return the maximum element (or element-based computation). 309 _.max = function(obj, iteratee, context) { 310 var result = -Infinity, lastComputed = -Infinity, 311 value, computed; 312 if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object') && obj != null) { 313 obj = isArrayLike(obj) ? obj : _.values(obj); 314 for (var i = 0, length = obj.length; i < length; i++) { 315 value = obj[i]; 316 if (value != null && value > result) { 317 result = value; 318 } 319 } 320 } else { 321 iteratee = cb(iteratee, context); 322 _.each(obj, function(v, index, list) { 323 computed = iteratee(v, index, list); 324 if (computed > lastComputed || computed === -Infinity && result === -Infinity) { 325 result = v; 326 lastComputed = computed; 327 } 328 }); 329 } 330 return result; 331 }; 332 333 // Return the minimum element (or element-based computation). 334 _.min = function(obj, iteratee, context) { 335 var result = Infinity, lastComputed = Infinity, 336 value, computed; 337 if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object') && obj != null) { 338 obj = isArrayLike(obj) ? obj : _.values(obj); 339 for (var i = 0, length = obj.length; i < length; i++) { 340 value = obj[i]; 341 if (value != null && value < result) { 342 result = value; 343 } 344 } 345 } else { 346 iteratee = cb(iteratee, context); 347 _.each(obj, function(v, index, list) { 348 computed = iteratee(v, index, list); 349 if (computed < lastComputed || computed === Infinity && result === Infinity) { 350 result = v; 351 lastComputed = computed; 352 } 353 }); 354 } 355 return result; 356 }; 357 358 // Shuffle a collection. 359 _.shuffle = function(obj) { 360 return _.sample(obj, Infinity); 361 }; 362 363 // Sample **n** random values from a collection using the modern version of the 364 // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). 365 // If **n** is not specified, returns a single random element. 366 // The internal `guard` argument allows it to work with `map`. 367 _.sample = function(obj, n, guard) { 368 if (n == null || guard) { 369 if (!isArrayLike(obj)) obj = _.values(obj); 370 return obj[_.random(obj.length - 1)]; 371 } 372 var sample = isArrayLike(obj) ? _.clone(obj) : _.values(obj); 373 var length = getLength(sample); 374 n = Math.max(Math.min(n, length), 0); 375 var last = length - 1; 376 for (var index = 0; index < n; index++) { 377 var rand = _.random(index, last); 378 var temp = sample[index]; 379 sample[index] = sample[rand]; 380 sample[rand] = temp; 381 } 382 return sample.slice(0, n); 383 }; 384 385 // Sort the object's values by a criterion produced by an iteratee. 386 _.sortBy = function(obj, iteratee, context) { 387 var index = 0; 388 iteratee = cb(iteratee, context); 389 return _.pluck(_.map(obj, function(value, key, list) { 390 return { 391 value: value, 392 index: index++, 393 criteria: iteratee(value, key, list) 394 }; 395 }).sort(function(left, right) { 396 var a = left.criteria; 397 var b = right.criteria; 398 if (a !== b) { 399 if (a > b || a === void 0) return 1; 400 if (a < b || b === void 0) return -1; 401 } 402 return left.index - right.index; 403 }), 'value'); 404 }; 405 406 // An internal function used for aggregate "group by" operations. 407 var group = function(behavior, partition) { 408 return function(obj, iteratee, context) { 409 var result = partition ? [[], []] : {}; 410 iteratee = cb(iteratee, context); 411 _.each(obj, function(value, index) { 412 var key = iteratee(value, index, obj); 413 behavior(result, value, key); 414 }); 415 return result; 416 }; 417 }; 418 419 // Groups the object's values by a criterion. Pass either a string attribute 420 // to group by, or a function that returns the criterion. 421 _.groupBy = group(function(result, value, key) { 422 if (_.has(result, key)) result[key].push(value); else result[key] = [value]; 423 }); 424 425 // Indexes the object's values by a criterion, similar to `groupBy`, but for 426 // when you know that your index values will be unique. 427 _.indexBy = group(function(result, value, key) { 428 result[key] = value; 429 }); 430 431 // Counts instances of an object that group by a certain criterion. Pass 432 // either a string attribute to count by, or a function that returns the 433 // criterion. 434 _.countBy = group(function(result, value, key) { 435 if (_.has(result, key)) result[key]++; else result[key] = 1; 436 }); 437 438 var reStrSymbol = /[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g; 439 // Safely create a real, live array from anything iterable. 440 _.toArray = function(obj) { 441 if (!obj) return []; 442 if (_.isArray(obj)) return slice.call(obj); 443 if (_.isString(obj)) { 444 // Keep surrogate pair characters together 445 return obj.match(reStrSymbol); 446 } 447 if (isArrayLike(obj)) return _.map(obj, _.identity); 448 return _.values(obj); 449 }; 450 451 // Return the number of elements in an object. 452 _.size = function(obj) { 453 if (obj == null) return 0; 454 return isArrayLike(obj) ? obj.length : _.keys(obj).length; 455 }; 456 457 // Split a collection into two arrays: one whose elements all satisfy the given 458 // predicate, and one whose elements all do not satisfy the predicate. 459 _.partition = group(function(result, value, pass) { 460 result[pass ? 0 : 1].push(value); 461 }, true); 462 463 // Array Functions 464 // --------------- 465 466 // Get the first element of an array. Passing **n** will return the first N 467 // values in the array. Aliased as `head` and `take`. The **guard** check 468 // allows it to work with `_.map`. 469 _.first = _.head = _.take = function(array, n, guard) { 470 if (array == null || array.length < 1) return void 0; 471 if (n == null || guard) return array[0]; 472 return _.initial(array, array.length - n); 473 }; 474 475 // Returns everything but the last entry of the array. Especially useful on 476 // the arguments object. Passing **n** will return all the values in 477 // the array, excluding the last N. 478 _.initial = function(array, n, guard) { 479 return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n))); 480 }; 481 482 // Get the last element of an array. Passing **n** will return the last N 483 // values in the array. 484 _.last = function(array, n, guard) { 485 if (array == null || array.length < 1) return void 0; 486 if (n == null || guard) return array[array.length - 1]; 487 return _.rest(array, Math.max(0, array.length - n)); 488 }; 489 490 // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. 491 // Especially useful on the arguments object. Passing an **n** will return 492 // the rest N values in the array. 493 _.rest = _.tail = _.drop = function(array, n, guard) { 494 return slice.call(array, n == null || guard ? 1 : n); 495 }; 496 497 // Trim out all falsy values from an array. 498 _.compact = function(array) { 499 return _.filter(array, Boolean); 500 }; 501 502 // Internal implementation of a recursive `flatten` function. 503 var flatten = function(input, shallow, strict, output) { 504 output = output || []; 505 var idx = output.length; 506 for (var i = 0, length = getLength(input); i < length; i++) { 507 var value = input[i]; 508 if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) { 509 // Flatten current level of array or arguments object. 510 if (shallow) { 511 var j = 0, len = value.length; 512 while (j < len) output[idx++] = value[j++]; 513 } else { 514 flatten(value, shallow, strict, output); 515 idx = output.length; 516 } 517 } else if (!strict) { 518 output[idx++] = value; 519 } 520 } 521 return output; 522 }; 523 524 // Flatten out an array, either recursively (by default), or just one level. 525 _.flatten = function(array, shallow) { 526 return flatten(array, shallow, false); 527 }; 528 529 // Return a version of the array that does not contain the specified value(s). 530 _.without = restArgs(function(array, otherArrays) { 531 return _.difference(array, otherArrays); 532 }); 533 534 // Produce a duplicate-free version of the array. If the array has already 535 // been sorted, you have the option of using a faster algorithm. 536 // Aliased as `unique`. 537 _.uniq = _.unique = function(array, isSorted, iteratee, context) { 538 if (!_.isBoolean(isSorted)) { 539 context = iteratee; 540 iteratee = isSorted; 541 isSorted = false; 542 } 543 if (iteratee != null) iteratee = cb(iteratee, context); 544 var result = []; 545 var seen = []; 546 for (var i = 0, length = getLength(array); i < length; i++) { 547 var value = array[i], 548 computed = iteratee ? iteratee(value, i, array) : value; 549 if (isSorted) { 550 if (!i || seen !== computed) result.push(value); 551 seen = computed; 552 } else if (iteratee) { 553 if (!_.contains(seen, computed)) { 554 seen.push(computed); 555 result.push(value); 556 } 557 } else if (!_.contains(result, value)) { 558 result.push(value); 559 } 560 } 561 return result; 562 }; 563 564 // Produce an array that contains the union: each distinct element from all of 565 // the passed-in arrays. 566 _.union = restArgs(function(arrays) { 567 return _.uniq(flatten(arrays, true, true)); 568 }); 569 570 // Produce an array that contains every item shared between all the 571 // passed-in arrays. 572 _.intersection = function(array) { 573 var result = []; 574 var argsLength = arguments.length; 575 for (var i = 0, length = getLength(array); i < length; i++) { 576 var item = array[i]; 577 if (_.contains(result, item)) continue; 578 var j; 579 for (j = 1; j < argsLength; j++) { 580 if (!_.contains(arguments[j], item)) break; 581 } 582 if (j === argsLength) result.push(item); 583 } 584 return result; 585 }; 586 587 // Take the difference between one array and a number of other arrays. 588 // Only the elements present in just the first array will remain. 589 _.difference = restArgs(function(array, rest) { 590 rest = flatten(rest, true, true); 591 return _.filter(array, function(value){ 592 return !_.contains(rest, value); 593 }); 594 }); 595 596 // Complement of _.zip. Unzip accepts an array of arrays and groups 597 // each array's elements on shared indices. 598 _.unzip = function(array) { 599 var length = array && _.max(array, getLength).length || 0; 600 var result = Array(length); 601 602 for (var index = 0; index < length; index++) { 603 result[index] = _.pluck(array, index); 604 } 605 return result; 606 }; 607 608 // Zip together multiple lists into a single array -- elements that share 609 // an index go together. 610 _.zip = restArgs(_.unzip); 611 612 // Converts lists into objects. Pass either a single array of `[key, value]` 613 // pairs, or two parallel arrays of the same length -- one of keys, and one of 614 // the corresponding values. 615 _.object = function(list, values) { 616 var result = {}; 617 for (var i = 0, length = getLength(list); i < length; i++) { 618 if (values) { 619 result[list[i]] = values[i]; 620 } else { 621 result[list[i][0]] = list[i][1]; 622 } 623 } 624 return result; 625 }; 626 627 // Generator function to create the findIndex and findLastIndex functions. 628 var createPredicateIndexFinder = function(dir) { 629 return function(array, predicate, context) { 630 predicate = cb(predicate, context); 631 var length = getLength(array); 632 var index = dir > 0 ? 0 : length - 1; 633 for (; index >= 0 && index < length; index += dir) { 634 if (predicate(array[index], index, array)) return index; 635 } 636 return -1; 637 }; 638 }; 639 640 // Returns the first index on an array-like that passes a predicate test. 641 _.findIndex = createPredicateIndexFinder(1); 642 _.findLastIndex = createPredicateIndexFinder(-1); 643 644 // Use a comparator function to figure out the smallest index at which 645 // an object should be inserted so as to maintain order. Uses binary search. 646 _.sortedIndex = function(array, obj, iteratee, context) { 647 iteratee = cb(iteratee, context, 1); 648 var value = iteratee(obj); 649 var low = 0, high = getLength(array); 650 while (low < high) { 651 var mid = Math.floor((low + high) / 2); 652 if (iteratee(array[mid]) < value) low = mid + 1; else high = mid; 653 } 654 return low; 655 }; 656 657 // Generator function to create the indexOf and lastIndexOf functions. 658 var createIndexFinder = function(dir, predicateFind, sortedIndex) { 659 return function(array, item, idx) { 660 var i = 0, length = getLength(array); 661 if (typeof idx == 'number') { 662 if (dir > 0) { 663 i = idx >= 0 ? idx : Math.max(idx + length, i); 664 } else { 665 length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1; 666 } 667 } else if (sortedIndex && idx && length) { 668 idx = sortedIndex(array, item); 669 return array[idx] === item ? idx : -1; 670 } 671 if (item !== item) { 672 idx = predicateFind(slice.call(array, i, length), _.isNaN); 673 return idx >= 0 ? idx + i : -1; 674 } 675 for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) { 676 if (array[idx] === item) return idx; 677 } 678 return -1; 679 }; 680 }; 681 682 // Return the position of the first occurrence of an item in an array, 683 // or -1 if the item is not included in the array. 684 // If the array is large and already in sort order, pass `true` 685 // for **isSorted** to use binary search. 686 _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex); 687 _.lastIndexOf = createIndexFinder(-1, _.findLastIndex); 688 689 // Generate an integer Array containing an arithmetic progression. A port of 690 // the native Python `range()` function. See 691 // [the Python documentation](http://docs.python.org/library/functions.html#range). 692 _.range = function(start, stop, step) { 693 if (stop == null) { 694 stop = start || 0; 695 start = 0; 696 } 697 if (!step) { 698 step = stop < start ? -1 : 1; 699 } 700 701 var length = Math.max(Math.ceil((stop - start) / step), 0); 702 var range = Array(length); 703 704 for (var idx = 0; idx < length; idx++, start += step) { 705 range[idx] = start; 706 } 707 708 return range; 709 }; 710 711 // Split an **array** into several arrays containing **count** or less elements 712 // of initial array. 713 _.chunk = function(array, count) { 714 if (count == null || count < 1) return []; 715 716 var result = []; 717 var i = 0, length = array.length; 718 while (i < length) { 719 result.push(slice.call(array, i, i += count)); 720 } 721 return result; 722 }; 723 724 // Function (ahem) Functions 725 // ------------------ 726 727 // Determines whether to execute a function as a constructor 728 // or a normal function with the provided arguments. 729 var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) { 730 if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args); 731 var self = baseCreate(sourceFunc.prototype); 732 var result = sourceFunc.apply(self, args); 733 if (_.isObject(result)) return result; 734 return self; 735 }; 736 737 // Create a function bound to a given object (assigning `this`, and arguments, 738 // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if 739 // available. 740 _.bind = restArgs(function(func, context, args) { 741 if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function'); 742 var bound = restArgs(function(callArgs) { 743 return executeBound(func, bound, context, this, args.concat(callArgs)); 744 }); 745 return bound; 746 }); 747 748 // Partially apply a function by creating a version that has had some of its 749 // arguments pre-filled, without changing its dynamic `this` context. _ acts 750 // as a placeholder by default, allowing any combination of arguments to be 751 // pre-filled. Set `_.partial.placeholder` for a custom placeholder argument. 752 _.partial = restArgs(function(func, boundArgs) { 753 var placeholder = _.partial.placeholder; 754 var bound = function() { 755 var position = 0, length = boundArgs.length; 756 var args = Array(length); 757 for (var i = 0; i < length; i++) { 758 args[i] = boundArgs[i] === placeholder ? arguments[position++] : boundArgs[i]; 759 } 760 while (position < arguments.length) args.push(arguments[position++]); 761 return executeBound(func, bound, this, this, args); 762 }; 763 return bound; 764 }); 765 766 _.partial.placeholder = _; 767 768 // Bind a number of an object's methods to that object. Remaining arguments 769 // are the method names to be bound. Useful for ensuring that all callbacks 770 // defined on an object belong to it. 771 _.bindAll = restArgs(function(obj, keys) { 772 keys = flatten(keys, false, false); 773 var index = keys.length; 774 if (index < 1) throw new Error('bindAll must be passed function names'); 775 while (index--) { 776 var key = keys[index]; 777 obj[key] = _.bind(obj[key], obj); 778 } 779 }); 780 781 // Memoize an expensive function by storing its results. 782 _.memoize = function(func, hasher) { 783 var memoize = function(key) { 784 var cache = memoize.cache; 785 var address = '' + (hasher ? hasher.apply(this, arguments) : key); 786 if (!_.has(cache, address)) cache[address] = func.apply(this, arguments); 787 return cache[address]; 788 }; 789 memoize.cache = {}; 790 return memoize; 791 }; 792 793 // Delays a function for the given number of milliseconds, and then calls 794 // it with the arguments supplied. 795 _.delay = restArgs(function(func, wait, args) { 796 return setTimeout(function() { 797 return func.apply(null, args); 798 }, wait); 799 }); 800 801 // Defers a function, scheduling it to run after the current call stack has 802 // cleared. 803 _.defer = _.partial(_.delay, _, 1); 804 805 // Returns a function, that, when invoked, will only be triggered at most once 806 // during a given window of time. Normally, the throttled function will run 807 // as much as it can, without ever going more than once per `wait` duration; 808 // but if you'd like to disable the execution on the leading edge, pass 809 // `{leading: false}`. To disable execution on the trailing edge, ditto. 810 _.throttle = function(func, wait, options) { 811 var timeout, context, args, result; 812 var previous = 0; 813 if (!options) options = {}; 814 815 var later = function() { 816 previous = options.leading === false ? 0 : _.now(); 817 timeout = null; 818 result = func.apply(context, args); 819 if (!timeout) context = args = null; 820 }; 821 822 var throttled = function() { 823 var now = _.now(); 824 if (!previous && options.leading === false) previous = now; 825 var remaining = wait - (now - previous); 826 context = this; 827 args = arguments; 828 if (remaining <= 0 || remaining > wait) { 829 if (timeout) { 830 clearTimeout(timeout); 831 timeout = null; 832 } 833 previous = now; 834 result = func.apply(context, args); 835 if (!timeout) context = args = null; 836 } else if (!timeout && options.trailing !== false) { 837 timeout = setTimeout(later, remaining); 838 } 839 return result; 840 }; 841 842 throttled.cancel = function() { 843 clearTimeout(timeout); 844 previous = 0; 845 timeout = context = args = null; 846 }; 847 848 return throttled; 849 }; 850 851 // Returns a function, that, as long as it continues to be invoked, will not 852 // be triggered. The function will be called after it stops being called for 853 // N milliseconds. If `immediate` is passed, trigger the function on the 854 // leading edge, instead of the trailing. 855 _.debounce = function(func, wait, immediate) { 856 var timeout, result; 857 858 var later = function(context, args) { 859 timeout = null; 860 if (args) result = func.apply(context, args); 861 }; 862 863 var debounced = restArgs(function(args) { 864 if (timeout) clearTimeout(timeout); 865 if (immediate) { 866 var callNow = !timeout; 867 timeout = setTimeout(later, wait); 868 if (callNow) result = func.apply(this, args); 869 } else { 870 timeout = _.delay(later, wait, this, args); 871 } 872 873 return result; 874 }); 875 876 debounced.cancel = function() { 877 clearTimeout(timeout); 878 timeout = null; 879 }; 880 881 return debounced; 882 }; 883 884 // Returns the first function passed as an argument to the second, 885 // allowing you to adjust arguments, run code before and after, and 886 // conditionally execute the original function. 887 _.wrap = function(func, wrapper) { 888 return _.partial(wrapper, func); 889 }; 890 891 // Returns a negated version of the passed-in predicate. 892 _.negate = function(predicate) { 893 return function() { 894 return !predicate.apply(this, arguments); 895 }; 896 }; 897 898 // Returns a function that is the composition of a list of functions, each 899 // consuming the return value of the function that follows. 900 _.compose = function() { 901 var args = arguments; 902 var start = args.length - 1; 903 return function() { 904 var i = start; 905 var result = args[start].apply(this, arguments); 906 while (i--) result = args[i].call(this, result); 907 return result; 908 }; 909 }; 910 911 // Returns a function that will only be executed on and after the Nth call. 912 _.after = function(times, func) { 913 return function() { 914 if (--times < 1) { 915 return func.apply(this, arguments); 916 } 917 }; 918 }; 919 920 // Returns a function that will only be executed up to (but not including) the Nth call. 921 _.before = function(times, func) { 922 var memo; 923 return function() { 924 if (--times > 0) { 925 memo = func.apply(this, arguments); 926 } 927 if (times <= 1) func = null; 928 return memo; 929 }; 930 }; 931 932 // Returns a function that will be executed at most one time, no matter how 933 // often you call it. Useful for lazy initialization. 934 _.once = _.partial(_.before, 2); 935 936 _.restArgs = restArgs; 937 938 // Object Functions 939 // ---------------- 940 941 // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed. 942 var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString'); 943 var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString', 944 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString']; 945 946 var collectNonEnumProps = function(obj, keys) { 947 var nonEnumIdx = nonEnumerableProps.length; 948 var constructor = obj.constructor; 949 var proto = _.isFunction(constructor) && constructor.prototype || ObjProto; 950 951 // Constructor is a special case. 952 var prop = 'constructor'; 953 if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop); 954 955 while (nonEnumIdx--) { 956 prop = nonEnumerableProps[nonEnumIdx]; 957 if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) { 958 keys.push(prop); 959 } 960 } 961 }; 962 963 // Retrieve the names of an object's own properties. 964 // Delegates to **ECMAScript 5**'s native `Object.keys`. 965 _.keys = function(obj) { 966 if (!_.isObject(obj)) return []; 967 if (nativeKeys) return nativeKeys(obj); 968 var keys = []; 969 for (var key in obj) if (_.has(obj, key)) keys.push(key); 970 // Ahem, IE < 9. 971 if (hasEnumBug) collectNonEnumProps(obj, keys); 972 return keys; 973 }; 974 975 // Retrieve all the property names of an object. 976 _.allKeys = function(obj) { 977 if (!_.isObject(obj)) return []; 978 var keys = []; 979 for (var key in obj) keys.push(key); 980 // Ahem, IE < 9. 981 if (hasEnumBug) collectNonEnumProps(obj, keys); 982 return keys; 983 }; 984 985 // Retrieve the values of an object's properties. 986 _.values = function(obj) { 987 var keys = _.keys(obj); 988 var length = keys.length; 989 var values = Array(length); 990 for (var i = 0; i < length; i++) { 991 values[i] = obj[keys[i]]; 992 } 993 return values; 994 }; 995 996 // Returns the results of applying the iteratee to each element of the object. 997 // In contrast to _.map it returns an object. 998 _.mapObject = function(obj, iteratee, context) { 999 iteratee = cb(iteratee, context); 1000 var keys = _.keys(obj), 1001 length = keys.length, 1002 results = {}; 1003 for (var index = 0; index < length; index++) { 1004 var currentKey = keys[index]; 1005 results[currentKey] = iteratee(obj[currentKey], currentKey, obj); 1006 } 1007 return results; 1008 }; 1009 1010 // Convert an object into a list of `[key, value]` pairs. 1011 _.pairs = function(obj) { 1012 var keys = _.keys(obj); 1013 var length = keys.length; 1014 var pairs = Array(length); 1015 for (var i = 0; i < length; i++) { 1016 pairs[i] = [keys[i], obj[keys[i]]]; 1017 } 1018 return pairs; 1019 }; 1020 1021 // Invert the keys and values of an object. The values must be serializable. 1022 _.invert = function(obj) { 1023 var result = {}; 1024 var keys = _.keys(obj); 1025 for (var i = 0, length = keys.length; i < length; i++) { 1026 result[obj[keys[i]]] = keys[i]; 1027 } 1028 return result; 1029 }; 1030 1031 // Return a sorted list of the function names available on the object. 1032 // Aliased as `methods`. 1033 _.functions = _.methods = function(obj) { 1034 var names = []; 1035 for (var key in obj) { 1036 if (_.isFunction(obj[key])) names.push(key); 1037 } 1038 return names.sort(); 1039 }; 1040 1041 // An internal function for creating assigner functions. 1042 var createAssigner = function(keysFunc, defaults) { 1043 return function(obj) { 1044 var length = arguments.length; 1045 if (defaults) obj = Object(obj); 1046 if (length < 2 || obj == null) return obj; 1047 for (var index = 1; index < length; index++) { 1048 var source = arguments[index], 1049 keys = keysFunc(source), 1050 l = keys.length; 1051 for (var i = 0; i < l; i++) { 1052 var key = keys[i]; 1053 if (!defaults || obj[key] === void 0) obj[key] = source[key]; 1054 } 1055 } 1056 return obj; 1057 }; 1058 }; 1059 1060 // Extend a given object with all the properties in passed-in object(s). 1061 _.extend = createAssigner(_.allKeys); 1062 1063 // Assigns a given object with all the own properties in the passed-in object(s). 1064 // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) 1065 _.extendOwn = _.assign = createAssigner(_.keys); 1066 1067 // Returns the first key on an object that passes a predicate test. 1068 _.findKey = function(obj, predicate, context) { 1069 predicate = cb(predicate, context); 1070 var keys = _.keys(obj), key; 1071 for (var i = 0, length = keys.length; i < length; i++) { 1072 key = keys[i]; 1073 if (predicate(obj[key], key, obj)) return key; 1074 } 1075 }; 1076 1077 // Internal pick helper function to determine if `obj` has key `key`. 1078 var keyInObj = function(value, key, obj) { 1079 return key in obj; 1080 }; 1081 1082 // Return a copy of the object only containing the whitelisted properties. 1083 _.pick = restArgs(function(obj, keys) { 1084 var result = {}, iteratee = keys[0]; 1085 if (obj == null) return result; 1086 if (_.isFunction(iteratee)) { 1087 if (keys.length > 1) iteratee = optimizeCb(iteratee, keys[1]); 1088 keys = _.allKeys(obj); 1089 } else { 1090 iteratee = keyInObj; 1091 keys = flatten(keys, false, false); 1092 obj = Object(obj); 1093 } 1094 for (var i = 0, length = keys.length; i < length; i++) { 1095 var key = keys[i]; 1096 var value = obj[key]; 1097 if (iteratee(value, key, obj)) result[key] = value; 1098 } 1099 return result; 1100 }); 1101 1102 // Return a copy of the object without the blacklisted properties. 1103 _.omit = restArgs(function(obj, keys) { 1104 var iteratee = keys[0], context; 1105 if (_.isFunction(iteratee)) { 1106 iteratee = _.negate(iteratee); 1107 if (keys.length > 1) context = keys[1]; 1108 } else { 1109 keys = _.map(flatten(keys, false, false), String); 1110 iteratee = function(value, key) { 1111 return !_.contains(keys, key); 1112 }; 1113 } 1114 return _.pick(obj, iteratee, context); 1115 }); 1116 1117 // Fill in a given object with default properties. 1118 _.defaults = createAssigner(_.allKeys, true); 1119 1120 // Creates an object that inherits from the given prototype object. 1121 // If additional properties are provided then they will be added to the 1122 // created object. 1123 _.create = function(prototype, props) { 1124 var result = baseCreate(prototype); 1125 if (props) _.extendOwn(result, props); 1126 return result; 1127 }; 1128 1129 // Create a (shallow-cloned) duplicate of an object. 1130 _.clone = function(obj) { 1131 if (!_.isObject(obj)) return obj; 1132 return _.isArray(obj) ? obj.slice() : _.extend({}, obj); 1133 }; 1134 1135 // Invokes interceptor with the obj, and then returns obj. 1136 // The primary purpose of this method is to "tap into" a method chain, in 1137 // order to perform operations on intermediate results within the chain. 1138 _.tap = function(obj, interceptor) { 1139 interceptor(obj); 1140 return obj; 1141 }; 1142 1143 // Returns whether an object has a given set of `key:value` pairs. 1144 _.isMatch = function(object, attrs) { 1145 var keys = _.keys(attrs), length = keys.length; 1146 if (object == null) return !length; 1147 var obj = Object(object); 1148 for (var i = 0; i < length; i++) { 1149 var key = keys[i]; 1150 if (attrs[key] !== obj[key] || !(key in obj)) return false; 1151 } 1152 return true; 1153 }; 1154 1155 1156 // Internal recursive comparison function for `isEqual`. 1157 var eq, deepEq; 1158 eq = function(a, b, aStack, bStack) { 1159 // Identical objects are equal. `0 === -0`, but they aren't identical. 1160 // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). 1161 if (a === b) return a !== 0 || 1 / a === 1 / b; 1162 // A strict comparison is necessary because `null == undefined`. 1163 if (a == null || b == null) return a === b; 1164 // `NaN`s are equivalent, but non-reflexive. 1165 if (a !== a) return b !== b; 1166 // Exhaust primitive checks 1167 var type = typeof a; 1168 if (type !== 'function' && type !== 'object' && typeof b != 'object') return false; 1169 return deepEq(a, b, aStack, bStack); 1170 }; 1171 1172 // Internal recursive comparison function for `isEqual`. 1173 deepEq = function(a, b, aStack, bStack) { 1174 // Unwrap any wrapped objects. 1175 if (a instanceof _) a = a._wrapped; 1176 if (b instanceof _) b = b._wrapped; 1177 // Compare `[[Class]]` names. 1178 var className = toString.call(a); 1179 if (className !== toString.call(b)) return false; 1180 switch (className) { 1181 // Strings, numbers, regular expressions, dates, and booleans are compared by value. 1182 case '[object RegExp]': 1183 // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i') 1184 case '[object String]': 1185 // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is 1186 // equivalent to `new String("5")`. 1187 return '' + a === '' + b; 1188 case '[object Number]': 1189 // `NaN`s are equivalent, but non-reflexive. 1190 // Object(NaN) is equivalent to NaN. 1191 if (+a !== +a) return +b !== +b; 1192 // An `egal` comparison is performed for other numeric values. 1193 return +a === 0 ? 1 / +a === 1 / b : +a === +b; 1194 case '[object Date]': 1195 case '[object Boolean]': 1196 // Coerce dates and booleans to numeric primitive values. Dates are compared by their 1197 // millisecond representations. Note that invalid dates with millisecond representations 1198 // of `NaN` are not equivalent. 1199 return +a === +b; 1200 case '[object Symbol]': 1201 return SymbolProto.valueOf.call(a) === SymbolProto.valueOf.call(b); 1202 } 1203 1204 var areArrays = className === '[object Array]'; 1205 if (!areArrays) { 1206 if (typeof a != 'object' || typeof b != 'object') return false; 1207 1208 // Objects with different constructors are not equivalent, but `Object`s or `Array`s 1209 // from different frames are. 1210 var aCtor = a.constructor, bCtor = b.constructor; 1211 if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor && 1212 _.isFunction(bCtor) && bCtor instanceof bCtor) 1213 && ('constructor' in a && 'constructor' in b)) { 1214 return false; 1215 } 1216 } 1217 // Assume equality for cyclic structures. The algorithm for detecting cyclic 1218 // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. 1219 1220 // Initializing stack of traversed objects. 1221 // It's done here since we only need them for objects and arrays comparison. 1222 aStack = aStack || []; 1223 bStack = bStack || []; 1224 var length = aStack.length; 1225 while (length--) { 1226 // Linear search. Performance is inversely proportional to the number of 1227 // unique nested structures. 1228 if (aStack[length] === a) return bStack[length] === b; 1229 } 1230 1231 // Add the first object to the stack of traversed objects. 1232 aStack.push(a); 1233 bStack.push(b); 1234 1235 // Recursively compare objects and arrays. 1236 if (areArrays) { 1237 // Compare array lengths to determine if a deep comparison is necessary. 1238 length = a.length; 1239 if (length !== b.length) return false; 1240 // Deep compare the contents, ignoring non-numeric properties. 1241 while (length--) { 1242 if (!eq(a[length], b[length], aStack, bStack)) return false; 1243 } 1244 } else { 1245 // Deep compare objects. 1246 var keys = _.keys(a), key; 1247 length = keys.length; 1248 // Ensure that both objects contain the same number of properties before comparing deep equality. 1249 if (_.keys(b).length !== length) return false; 1250 while (length--) { 1251 // Deep compare each member 1252 key = keys[length]; 1253 if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false; 1254 } 1255 } 1256 // Remove the first object from the stack of traversed objects. 1257 aStack.pop(); 1258 bStack.pop(); 1259 return true; 1260 }; 1261 1262 // Perform a deep comparison to check if two objects are equal. 1263 _.isEqual = function(a, b) { 1264 return eq(a, b); 1265 }; 1266 1267 // Is a given array, string, or object empty? 1268 // An "empty" object has no enumerable own-properties. 1269 _.isEmpty = function(obj) { 1270 if (obj == null) return true; 1271 if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0; 1272 return _.keys(obj).length === 0; 1273 }; 1274 1275 // Is a given value a DOM element? 1276 _.isElement = function(obj) { 1277 return !!(obj && obj.nodeType === 1); 1278 }; 1279 1280 // Is a given value an array? 1281 // Delegates to ECMA5's native Array.isArray 1282 _.isArray = nativeIsArray || function(obj) { 1283 return toString.call(obj) === '[object Array]'; 1284 }; 1285 1286 // Is a given variable an object? 1287 _.isObject = function(obj) { 1288 var type = typeof obj; 1289 return type === 'function' || type === 'object' && !!obj; 1290 }; 1291 1292 // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError, isMap, isWeakMap, isSet, isWeakSet. 1293 _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error', 'Symbol', 'Map', 'WeakMap', 'Set', 'WeakSet'], function(name) { 1294 _['is' + name] = function(obj) { 1295 return toString.call(obj) === '[object ' + name + ']'; 1296 }; 1297 }); 1298 1299 // Define a fallback version of the method in browsers (ahem, IE < 9), where 1300 // there isn't any inspectable "Arguments" type. 1301 if (!_.isArguments(arguments)) { 1302 _.isArguments = function(obj) { 1303 return _.has(obj, 'callee'); 1304 }; 1305 } 1306 1307 // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8, 1308 // IE 11 (#1621), Safari 8 (#1929), and PhantomJS (#2236). 1309 var nodelist = root.document && root.document.childNodes; 1310 if (typeof /./ != 'function' && typeof Int8Array != 'object' && typeof nodelist != 'function') { 1311 _.isFunction = function(obj) { 1312 return typeof obj == 'function' || false; 1313 }; 1314 } 1315 1316 // Is a given object a finite number? 1317 _.isFinite = function(obj) { 1318 return !_.isSymbol(obj) && isFinite(obj) && !isNaN(parseFloat(obj)); 1319 }; 1320 1321 // Is the given value `NaN`? 1322 _.isNaN = function(obj) { 1323 return _.isNumber(obj) && isNaN(obj); 1324 }; 1325 1326 // Is a given value a boolean? 1327 _.isBoolean = function(obj) { 1328 return obj === true || obj === false || toString.call(obj) === '[object Boolean]'; 1329 }; 1330 1331 // Is a given value equal to null? 1332 _.isNull = function(obj) { 1333 return obj === null; 1334 }; 1335 1336 // Is a given variable undefined? 1337 _.isUndefined = function(obj) { 1338 return obj === void 0; 1339 }; 1340 1341 // Shortcut function for checking if an object has a given property directly 1342 // on itself (in other words, not on a prototype). 1343 _.has = function(obj, key) { 1344 return obj != null && hasOwnProperty.call(obj, key); 1345 }; 1346 1347 // Utility Functions 1348 // ----------------- 1349 1350 // Run Underscore.js in *noConflict* mode, returning the `_` variable to its 1351 // previous owner. Returns a reference to the Underscore object. 1352 _.noConflict = function() { 1353 root._ = previousUnderscore; 1354 return this; 1355 }; 1356 1357 // Keep the identity function around for default iteratees. 1358 _.identity = function(value) { 1359 return value; 1360 }; 1361 1362 // Predicate-generating functions. Often useful outside of Underscore. 1363 _.constant = function(value) { 1364 return function() { 1365 return value; 1366 }; 1367 }; 1368 1369 _.noop = function(){}; 1370 1371 _.property = property; 1372 1373 // Generates a function for a given object that returns a given property. 1374 _.propertyOf = function(obj) { 1375 return obj == null ? function(){} : function(key) { 1376 return obj[key]; 1377 }; 1378 }; 1379 1380 // Returns a predicate for checking whether an object has a given set of 1381 // `key:value` pairs. 1382 _.matcher = _.matches = function(attrs) { 1383 attrs = _.extendOwn({}, attrs); 1384 return function(obj) { 1385 return _.isMatch(obj, attrs); 1386 }; 1387 }; 1388 1389 // Run a function **n** times. 1390 _.times = function(n, iteratee, context) { 1391 var accum = Array(Math.max(0, n)); 1392 iteratee = optimizeCb(iteratee, context, 1); 1393 for (var i = 0; i < n; i++) accum[i] = iteratee(i); 1394 return accum; 1395 }; 1396 1397 // Return a random integer between min and max (inclusive). 1398 _.random = function(min, max) { 1399 if (max == null) { 1400 max = min; 1401 min = 0; 1402 } 1403 return min + Math.floor(Math.random() * (max - min + 1)); 1404 }; 1405 1406 // A (possibly faster) way to get the current timestamp as an integer. 1407 _.now = Date.now || function() { 1408 return new Date().getTime(); 1409 }; 1410 1411 // List of HTML entities for escaping. 1412 var escapeMap = { 1413 '&': '&', 1414 '<': '<', 1415 '>': '>', 1416 '"': '"', 1417 "'": ''', 1418 '`': '`' 1419 }; 1420 var unescapeMap = _.invert(escapeMap); 1421 1422 // Functions for escaping and unescaping strings to/from HTML interpolation. 1423 var createEscaper = function(map) { 1424 var escaper = function(match) { 1425 return map[match]; 1426 }; 1427 // Regexes for identifying a key that needs to be escaped. 1428 var source = '(?:' + _.keys(map).join('|') + ')'; 1429 var testRegexp = RegExp(source); 1430 var replaceRegexp = RegExp(source, 'g'); 1431 return function(string) { 1432 string = string == null ? '' : '' + string; 1433 return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; 1434 }; 1435 }; 1436 _.escape = createEscaper(escapeMap); 1437 _.unescape = createEscaper(unescapeMap); 1438 1439 // If the value of the named `property` is a function then invoke it with the 1440 // `object` as context; otherwise, return it. 1441 _.result = function(object, prop, fallback) { 1442 var value = object == null ? void 0 : object[prop]; 1443 if (value === void 0) { 1444 value = fallback; 1445 } 1446 return _.isFunction(value) ? value.call(object) : value; 1447 }; 1448 1449 // Generate a unique integer id (unique within the entire client session). 1450 // Useful for temporary DOM ids. 1451 var idCounter = 0; 1452 _.uniqueId = function(prefix) { 1453 var id = ++idCounter + ''; 1454 return prefix ? prefix + id : id; 1455 }; 1456 1457 // By default, Underscore uses ERB-style template delimiters, change the 1458 // following template settings to use alternative delimiters. 1459 _.templateSettings = { 1460 evaluate: /<%([\s\S]+?)%>/g, 1461 interpolate: /<%=([\s\S]+?)%>/g, 1462 escape: /<%-([\s\S]+?)%>/g 1463 }; 1464 1465 // When customizing `templateSettings`, if you don't want to define an 1466 // interpolation, evaluation or escaping regex, we need one that is 1467 // guaranteed not to match. 1468 var noMatch = /(.)^/; 1469 1470 // Certain characters need to be escaped so that they can be put into a 1471 // string literal. 1472 var escapes = { 1473 "'": "'", 1474 '\\': '\\', 1475 '\r': 'r', 1476 '\n': 'n', 1477 '\u2028': 'u2028', 1478 '\u2029': 'u2029' 1479 }; 1480 1481 var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g; 1482 1483 var escapeChar = function(match) { 1484 return '\\' + escapes[match]; 1485 }; 1486 1487 // JavaScript micro-templating, similar to John Resig's implementation. 1488 // Underscore templating handles arbitrary delimiters, preserves whitespace, 1489 // and correctly escapes quotes within interpolated code. 1490 // NB: `oldSettings` only exists for backwards compatibility. 1491 _.template = function(text, settings, oldSettings) { 1492 if (!settings && oldSettings) settings = oldSettings; 1493 settings = _.defaults({}, settings, _.templateSettings); 1494 1495 // Combine delimiters into one regular expression via alternation. 1496 var matcher = RegExp([ 1497 (settings.escape || noMatch).source, 1498 (settings.interpolate || noMatch).source, 1499 (settings.evaluate || noMatch).source 1500 ].join('|') + '|$', 'g'); 1501 1502 // Compile the template source, escaping string literals appropriately. 1503 var index = 0; 1504 var source = "__p+='"; 1505 text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { 1506 source += text.slice(index, offset).replace(escapeRegExp, escapeChar); 1507 index = offset + match.length; 1508 1509 if (escape) { 1510 source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; 1511 } else if (interpolate) { 1512 source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; 1513 } else if (evaluate) { 1514 source += "';\n" + evaluate + "\n__p+='"; 1515 } 1516 1517 // Adobe VMs need the match returned to produce the correct offset. 1518 return match; 1519 }); 1520 source += "';\n"; 1521 1522 // If a variable is not specified, place data values in local scope. 1523 if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; 1524 1525 source = "var __t,__p='',__j=Array.prototype.join," + 1526 "print=function(){__p+=__j.call(arguments,'');};\n" + 1527 source + 'return __p;\n'; 1528 1529 var render; 1530 try { 1531 render = new Function(settings.variable || 'obj', '_', source); 1532 } catch (e) { 1533 e.source = source; 1534 throw e; 1535 } 1536 1537 var template = function(data) { 1538 return render.call(this, data, _); 1539 }; 1540 1541 // Provide the compiled source as a convenience for precompilation. 1542 var argument = settings.variable || 'obj'; 1543 template.source = 'function(' + argument + '){\n' + source + '}'; 1544 1545 return template; 1546 }; 1547 1548 // Add a "chain" function. Start chaining a wrapped Underscore object. 1549 _.chain = function(obj) { 1550 var instance = _(obj); 1551 instance._chain = true; 1552 return instance; 1553 }; 1554 1555 // OOP 1556 // --------------- 1557 // If Underscore is called as a function, it returns a wrapped object that 1558 // can be used OO-style. This wrapper holds altered versions of all the 1559 // underscore functions. Wrapped objects may be chained. 1560 1561 // Helper function to continue chaining intermediate results. 1562 var chainResult = function(instance, obj) { 1563 return instance._chain ? _(obj).chain() : obj; 1564 }; 1565 1566 // Add your own custom functions to the Underscore object. 1567 _.mixin = function(obj) { 1568 _.each(_.functions(obj), function(name) { 1569 var func = _[name] = obj[name]; 1570 _.prototype[name] = function() { 1571 var args = [this._wrapped]; 1572 push.apply(args, arguments); 1573 return chainResult(this, func.apply(_, args)); 1574 }; 1575 }); 1576 return _; 1577 }; 1578 1579 // Add all of the Underscore functions to the wrapper object. 1580 _.mixin(_); 1581 1582 // Add all mutator Array functions to the wrapper. 1583 _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { 1584 var method = ArrayProto[name]; 1585 _.prototype[name] = function() { 1586 var obj = this._wrapped; 1587 method.apply(obj, arguments); 1588 if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0]; 1589 return chainResult(this, obj); 1590 }; 1591 }); 1592 1593 // Add all accessor Array functions to the wrapper. 1594 _.each(['concat', 'join', 'slice'], function(name) { 1595 var method = ArrayProto[name]; 1596 _.prototype[name] = function() { 1597 return chainResult(this, method.apply(this._wrapped, arguments)); 1598 }; 1599 }); 1600 1601 // Extracts the result from a wrapped and chained object. 1602 _.prototype.value = function() { 1603 return this._wrapped; 1604 }; 1605 1606 // Provide unwrapping proxy for some methods used in engine operations 1607 // such as arithmetic and JSON stringification. 1608 _.prototype.valueOf = _.prototype.toJSON = _.prototype.value; 1609 1610 _.prototype.toString = function() { 1611 return String(this._wrapped); 1612 }; 1613 1614 // AMD registration happens at the end for compatibility with AMD loaders 1615 // that may not enforce next-turn semantics on modules. Even though general 1616 // practice for AMD registration is to be anonymous, underscore registers 1617 // as a named module because, like jQuery, it is a base library that is 1618 // popular enough to be bundled in a third party lib, but not be part of 1619 // an AMD load request. Those cases could generate an error when an 1620 // anonymous define() is called outside of a loader request. 1621 if (typeof define == 'function' && define.amd) { 1622 define('underscore', [], function() { 1623 return _; 1624 }); 1625 } 1626}()); 1627