-(function() {
diff --git a/docs/underscore.html b/docs/underscore.html index 2170598b4..b5855968b 100644 --- a/docs/underscore.html +++ b/docs/underscore.html @@ -29,13 +29,13 @@
Underscore.js 1.8.3
http://underscorejs.org
-(c) 2009-2017 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+(c) 2009-2017 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
Underscore may be freely distributed under the MIT license.
-(function() {
Establish the root object, window
in the browser, or exports
on the server.
Establish the root object, window
(self
) in the browser, global
+on the server, or this
in some virtual machines. We use self
+instead of window
for WebWorker
support.
var root = this;
var root = typeof self == 'object' && self.self === self && self ||
+ typeof global == 'object' && global.global === global && global ||
+ this ||
+ {};
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
var ArrayProto = Array.prototype, ObjProto = Object.prototype;
+ var SymbolProto = typeof Symbol !== 'undefined' ? Symbol.prototype : null;
var
- push = ArrayProto.push,
- slice = ArrayProto.slice,
- toString = ObjProto.toString,
- hasOwnProperty = ObjProto.hasOwnProperty;
var push = ArrayProto.push,
+ slice = ArrayProto.slice,
+ toString = ObjProto.toString,
+ hasOwnProperty = ObjProto.hasOwnProperty;
var
- nativeIsArray = Array.isArray,
- nativeKeys = Object.keys,
- nativeBind = FuncProto.bind,
- nativeCreate = Object.create;
var nativeIsArray = Array.isArray,
+ nativeKeys = Object.keys,
+ nativeCreate = Object.create;
var Ctor = function(){};
var Ctor = function(){};
var _ = function(obj) {
+ var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
@@ -190,13 +193,15 @@ Baseline setup
¶
Export the Underscore object for Node.js, with
-backwards-compatibility for the old require()
API. If we’re in
-the browser, add _
as a global object.
+backwards-compatibility for their old module API. If we’re in
+the browser, add _
as a global object.
+(nodeType
is checked to ensure that module
+and exports
are not HTML elements.)
- if (typeof exports !== 'undefined') {
- if (typeof module !== 'undefined' && module.exports) {
+ if (typeof exports != 'undefined' && !exports.nodeType) {
+ if (typeof module != 'undefined' && !module.nodeType && module.exports) {
exports = module.exports = _;
}
exports._ = _;
@@ -234,96 +239,135 @@ Baseline setup
- var optimizeCb = function(func, context, argCount) {
+ var optimizeCb = function(func, context, argCount) {
if (context === void 0) return func;
- switch (argCount == null ? 3 : argCount) {
- case 1: return function(value) {
+ switch (argCount) {
+ case 1: return function(value) {
return func.call(context, value);
- };
- case 2: return function(value, other) {
- return func.call(context, value, other);
- };
- case 3: return function(value, index, collection) {
+ };
+
+
+
+
+
+
+
+
+ ¶
+
+ The 2-parameter case has been omitted only because no current consumers
+made use of it.
+
+
+
+ case null:
+ case 3: return function(value, index, collection) {
return func.call(context, value, index, collection);
};
- case 4: return function(accumulator, value, index, collection) {
+ case 4: return function(accumulator, value, index, collection) {
return func.call(context, accumulator, value, index, collection);
};
}
- return function() {
+ return function() {
return func.apply(context, arguments);
};
- };
+ };
+
+ var builtinIteratee;
-
+
- A mostly-internal function to generate callbacks that can be applied
-to each element in a collection, returning the desired result — either
-identity, an arbitrary callback, a property matcher, or a property accessor.
+ An internal function to generate callbacks that can be applied to each
+element in a collection, returning the desired result — either identity
,
+an arbitrary callback, a property matcher, or a property accessor.
- var cb = function(value, context, argCount) {
+ var cb = function(value, context, argCount) {
+ if (_.iteratee !== builtinIteratee) return _.iteratee(value, context);
if (value == null) return _.identity;
if (_.isFunction(value)) return optimizeCb(value, context, argCount);
- if (_.isObject(value)) return _.matcher(value);
+ if (_.isObject(value) && !_.isArray(value)) return _.matcher(value);
return _.property(value);
- };
- _.iteratee = function(value, context) {
+ };
+
+
+
+
+
+
+
+
+ ¶
+
+ External wrapper for our callback generator. Users may customize
+_.iteratee
if they want additional predicate/iteratee shorthand styles.
+This abstraction hides the internal-only argCount argument.
+
+
+
+ _.iteratee = builtinIteratee = function(value, context) {
return cb(value, context, Infinity);
};
-
+
- An internal function for creating assigner functions.
+ Similar to ES6’s rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html)
+This accumulates the arguments passed into an array, after a given index.
- var createAssigner = function(keysFunc, undefinedOnly) {
- return function(obj) {
- var length = arguments.length;
- if (length < 2 || obj == null) return obj;
- for (var index = 1; index < length; index++) {
- var source = arguments[index],
- keys = keysFunc(source),
- l = keys.length;
- for (var i = 0; i < l; i++) {
- var key = keys[i];
- if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];
- }
+ var restArgs = function(func, startIndex) {
+ startIndex = startIndex == null ? func.length - 1 : +startIndex;
+ return function() {
+ var length = Math.max(arguments.length - startIndex, 0),
+ rest = Array(length),
+ index = 0;
+ for (; index < length; index++) {
+ rest[index] = arguments[index + startIndex];
}
- return obj;
+ switch (startIndex) {
+ case 0: return func.call(this, rest);
+ case 1: return func.call(this, arguments[0], rest);
+ case 2: return func.call(this, arguments[0], arguments[1], rest);
+ }
+ var args = Array(startIndex + 1);
+ for (index = 0; index < startIndex; index++) {
+ args[index] = arguments[index];
+ }
+ args[startIndex] = rest;
+ return func.apply(this, args);
};
};
-
+
- var baseCreate = function(prototype) {
+ var baseCreate = function(prototype) {
if (!_.isObject(prototype)) return {};
if (nativeCreate) return nativeCreate(prototype);
Ctor.prototype = prototype;
@@ -332,31 +376,40 @@ Baseline setup
return result;
};
- var property = function(key) {
- return function(obj) {
+ var shallowProperty = function(key) {
+ return function(obj) {
return obj == null ? void 0 : obj[key];
};
+ };
+
+ var deepGet = function(obj, path) {
+ var length = path.length;
+ for (var i = 0; i < length; i++) {
+ if (obj == null) return void 0;
+ obj = obj[path[i]];
+ }
+ return length ? obj : void 0;
};
-
+
Helper for collection methods to determine whether a collection
-should be iterated as an array or as an object
+should be iterated as an array or as an object.
Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
- var getLength = property('length');
- var isArrayLike = function(collection) {
+ var getLength = shallowProperty('length');
+ var isArrayLike = function(collection) {
var length = getLength(collection);
return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
};
@@ -364,11 +417,11 @@ Baseline setup
-
+
Collection Functions
@@ -377,11 +430,11 @@ Collection Functions
-
+
@@ -389,11 +442,11 @@ Collection Functions
-
+
The cornerstone, an each
implementation, aka forEach
.
Handles raw objects in addition to array-likes. Treats all
@@ -401,7 +454,7 @@
Collection Functions
- _.each = _.forEach = function(obj, iteratee, context) {
+ _.each = _.forEach = function(obj, iteratee, context) {
iteratee = optimizeCb(iteratee, context);
var i, length;
if (isArrayLike(obj)) {
@@ -420,17 +473,17 @@ Collection Functions
-
+
- _.map = _.collect = function(obj, iteratee, context) {
+ _.map = _.collect = function(obj, iteratee, context) {
iteratee = cb(iteratee, context);
var keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length,
@@ -445,75 +498,61 @@ Collection Functions
-
+
- function createReduce(dir) {
+ var createReduce = function(dir) {
-
+
- Optimized iterator function as using arguments.length
-in the main function will deoptimize the, see #1991.
+ Wrap code that reassigns argument variables in a separate function than
+the one that accesses arguments.length
to avoid a perf hit. (#1991)
- function iterator(obj, iteratee, memo, keys, index, length) {
+ var reducer = function(obj, iteratee, memo, initial) {
+ var keys = !isArrayLike(obj) && _.keys(obj),
+ length = (keys || obj).length,
+ index = dir > 0 ? 0 : length - 1;
+ if (!initial) {
+ memo = obj[keys ? keys[index] : index];
+ index += dir;
+ }
for (; index >= 0 && index < length; index += dir) {
var currentKey = keys ? keys[index] : index;
memo = iteratee(memo, obj[currentKey], currentKey, obj);
}
return memo;
- }
-
- return function(obj, iteratee, memo, context) {
- iteratee = optimizeCb(iteratee, context, 4);
- var keys = !isArrayLike(obj) && _.keys(obj),
- length = (keys || obj).length,
- index = dir > 0 ? 0 : length - 1;
-
-
-
-
-
-
-
-
- ¶
-
- Determine the initial value if none is provided.
+ };
-
-
- if (arguments.length < 3) {
- memo = obj[keys ? keys[index] : index];
- index += dir;
- }
- return iterator(obj, iteratee, memo, keys, index, length);
+ return function(obj, iteratee, memo, context) {
+ var initial = arguments.length >= 3;
+ return reducer(obj, optimizeCb(iteratee, context, 4), memo, initial);
};
- }
+ };
-
+
Reduce builds up a single result from a list of values, aka inject
,
or foldl
.
@@ -525,59 +564,55 @@ Collection Functions
-
+
- _.reduceRight = _.foldr = createReduce(-1);
+ _.reduceRight = _.foldr = createReduce(-1);
-
+
- _.find = _.detect = function(obj, predicate, context) {
- var key;
- if (isArrayLike(obj)) {
- key = _.findIndex(obj, predicate, context);
- } else {
- key = _.findKey(obj, predicate, context);
- }
- if (key !== void 0 && key !== -1) return obj[key];
+ _.find = _.detect = function(obj, predicate, context) {
+ var keyFinder = isArrayLike(obj) ? _.findIndex : _.findKey;
+ var key = keyFinder(obj, predicate, context);
+ if (key !== void 0 && key !== -1) return obj[key];
};
-
+
- _.filter = _.select = function(obj, predicate, context) {
+ _.filter = _.select = function(obj, predicate, context) {
var results = [];
predicate = cb(predicate, context);
- _.each(obj, function(value, index, list) {
+ _.each(obj, function(value, index, list) {
if (predicate(value, index, list)) results.push(value);
});
return results;
@@ -586,35 +621,35 @@ Collection Functions
-
+
- _.reject = function(obj, predicate, context) {
+ _.reject = function(obj, predicate, context) {
return _.filter(obj, _.negate(cb(predicate)), context);
};
-
+
- _.every = _.all = function(obj, predicate, context) {
+ _.every = _.all = function(obj, predicate, context) {
predicate = cb(predicate, context);
var keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length;
@@ -628,18 +663,18 @@ Collection Functions
-
+
- _.some = _.any = function(obj, predicate, context) {
+ _.some = _.any = function(obj, predicate, context) {
predicate = cb(predicate, context);
var keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length;
@@ -653,18 +688,18 @@ Collection Functions
-
+
Determine if the array or object contains a given item (using ===
).
Aliased as includes
and include
.
- _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {
+ _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {
if (!isArrayLike(obj)) obj = _.values(obj);
if (typeof fromIndex != 'number' || guard) fromIndex = 0;
return _.indexOf(obj, item, fromIndex) >= 0;
@@ -673,108 +708,120 @@ Collection Functions
-
+
- _.invoke = function(obj, method) {
- var args = slice.call(arguments, 2);
- var isFunc = _.isFunction(method);
- return _.map(obj, function(value) {
- var func = isFunc ? method : value[method];
- return func == null ? func : func.apply(value, args);
+ _.invoke = restArgs(function(obj, path, args) {
+ var contextPath, func;
+ if (_.isFunction(path)) {
+ func = path;
+ } else if (_.isArray(path)) {
+ contextPath = path.slice(0, -1);
+ path = path[path.length - 1];
+ }
+ return _.map(obj, function(context) {
+ var method = func;
+ if (!method) {
+ if (contextPath && contextPath.length) {
+ context = deepGet(context, contextPath);
+ }
+ if (context == null) return void 0;
+ method = context[path];
+ }
+ return method == null ? method : method.apply(context, args);
});
- };
+ });
-
+
- _.pluck = function(obj, key) {
+ _.pluck = function(obj, key) {
return _.map(obj, _.property(key));
};
-
+
Convenience version of a common use case of filter
: selecting only objects
containing specific key:value
pairs.
- _.where = function(obj, attrs) {
+ _.where = function(obj, attrs) {
return _.filter(obj, _.matcher(attrs));
};
-
+
Convenience version of a common use case of find
: getting the first object
containing specific key:value
pairs.
- _.findWhere = function(obj, attrs) {
+ _.findWhere = function(obj, attrs) {
return _.find(obj, _.matcher(attrs));
};
-
+
- _.max = function(obj, iteratee, context) {
+ _.max = function(obj, iteratee, context) {
var result = -Infinity, lastComputed = -Infinity,
value, computed;
- if (iteratee == null && obj != null) {
+ if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object') && obj != null) {
obj = isArrayLike(obj) ? obj : _.values(obj);
for (var i = 0, length = obj.length; i < length; i++) {
value = obj[i];
- if (value > result) {
+ if (value != null && value > result) {
result = value;
}
}
} else {
iteratee = cb(iteratee, context);
- _.each(obj, function(value, index, list) {
- computed = iteratee(value, index, list);
+ _.each(obj, function(v, index, list) {
+ computed = iteratee(v, index, list);
if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
- result = value;
+ result = v;
lastComputed = computed;
}
});
@@ -785,33 +832,33 @@ Collection Functions
-
+
- _.min = function(obj, iteratee, context) {
+ _.min = function(obj, iteratee, context) {
var result = Infinity, lastComputed = Infinity,
value, computed;
- if (iteratee == null && obj != null) {
+ if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object') && obj != null) {
obj = isArrayLike(obj) ? obj : _.values(obj);
for (var i = 0, length = obj.length; i < length; i++) {
value = obj[i];
- if (value < result) {
+ if (value != null && value < result) {
result = value;
}
}
} else {
iteratee = cb(iteratee, context);
- _.each(obj, function(value, index, list) {
- computed = iteratee(value, index, list);
+ _.each(obj, function(v, index, list) {
+ computed = iteratee(v, index, list);
if (computed < lastComputed || computed === Infinity && result === Infinity) {
- result = value;
+ result = v;
lastComputed = computed;
}
});
@@ -822,79 +869,82 @@ Collection Functions
-
+
- Shuffle a collection, using the modern version of the
-Fisher-Yates shuffle.
+ Shuffle a collection.
- _.shuffle = function(obj) {
- var set = isArrayLike(obj) ? obj : _.values(obj);
- var length = set.length;
- var shuffled = Array(length);
- for (var index = 0, rand; index < length; index++) {
- rand = _.random(0, index);
- if (rand !== index) shuffled[index] = shuffled[rand];
- shuffled[rand] = set[index];
- }
- return shuffled;
+ _.shuffle = function(obj) {
+ return _.sample(obj, Infinity);
};
-
+
- Sample n random values from a collection.
+
Sample n random values from a collection using the modern version of the
+Fisher-Yates shuffle.
If n is not specified, returns a single random element.
The internal guard
argument allows it to work with map
.
- _.sample = function(obj, n, guard) {
+ _.sample = function(obj, n, guard) {
if (n == null || guard) {
if (!isArrayLike(obj)) obj = _.values(obj);
return obj[_.random(obj.length - 1)];
}
- return _.shuffle(obj).slice(0, Math.max(0, n));
+ var sample = isArrayLike(obj) ? _.clone(obj) : _.values(obj);
+ var length = getLength(sample);
+ n = Math.max(Math.min(n, length), 0);
+ var last = length - 1;
+ for (var index = 0; index < n; index++) {
+ var rand = _.random(index, last);
+ var temp = sample[index];
+ sample[index] = sample[rand];
+ sample[rand] = temp;
+ }
+ return sample.slice(0, n);
};
-
+
- _.sortBy = function(obj, iteratee, context) {
+ _.sortBy = function(obj, iteratee, context) {
+ var index = 0;
iteratee = cb(iteratee, context);
- return _.pluck(_.map(obj, function(value, index, list) {
+ return _.pluck(_.map(obj, function(value, key, list) {
return {
- value: value,
- index: index,
- criteria: iteratee(value, index, list)
+ value: value,
+ index: index++,
+ criteria: iteratee(value, key, list)
};
- }).sort(function(left, right) {
+ }).sort(function(left, right) {
var a = left.criteria;
var b = right.criteria;
if (a !== b) {
if (a > b || a === void 0) return 1;
- if (a < b || b === void 0) return -1;
+ if (a < b || b === void 0) return -1;
}
return left.index - right.index;
}), 'value');
@@ -903,21 +953,21 @@ Collection Functions
-
+
- var group = function(behavior) {
- return function(obj, iteratee, context) {
- var result = {};
+ var group = function(behavior, partition) {
+ return function(obj, iteratee, context) {
+ var result = partition ? [[], []] : {};
iteratee = cb(iteratee, context);
- _.each(obj, function(value, index) {
+ _.each(obj, function(value, index) {
var key = iteratee(value, index, obj);
behavior(result, value, key);
});
@@ -928,47 +978,47 @@ Collection Functions
-
+
Groups the object’s values by a criterion. Pass either a string attribute
to group by, or a function that returns the criterion.
- _.groupBy = group(function(result, value, key) {
+ _.groupBy = group(function(result, value, key) {
if (_.has(result, key)) result[key].push(value); else result[key] = [value];
});
-
+
Indexes the object’s values by a criterion, similar to groupBy
, but for
when you know that your index values will be unique.
- _.indexBy = group(function(result, value, key) {
+ _.indexBy = group(function(result, value, key) {
result[key] = value;
});
-
+
Counts instances of an object that group by a certain criterion. Pass
either a string attribute to count by, or a function that returns the
@@ -976,26 +1026,45 @@
Collection Functions
- _.countBy = group(function(result, value, key) {
+ _.countBy = group(function(result, value, key) {
if (_.has(result, key)) result[key]++; else result[key] = 1;
- });
+ });
+
+ var reStrSymbol = /[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g;
-
+
- _.toArray = function(obj) {
+ _.toArray = function(obj) {
if (!obj) return [];
if (_.isArray(obj)) return slice.call(obj);
+ if (_.isString(obj)) {
+
+
+
+
+
+
+
+
+ ¶
+
+ Keep surrogate pair characters together
+
+
+
+ return obj.match(reStrSymbol);
+ }
if (isArrayLike(obj)) return _.map(obj, _.identity);
return _.values(obj);
};
@@ -1003,17 +1072,17 @@ Collection Functions
-
+
- _.size = function(obj) {
+ _.size = function(obj) {
if (obj == null) return 0;
return isArrayLike(obj) ? obj.length : _.keys(obj).length;
};
@@ -1021,65 +1090,42 @@ Collection Functions
-
+
Split a collection into two arrays: one whose elements all satisfy the given
predicate, and one whose elements all do not satisfy the predicate.
- _.partition = function(obj, predicate, context) {
- predicate = cb(predicate, context);
- var pass = [], fail = [];
- _.each(obj, function(value, key, obj) {
- (predicate(value, key, obj) ? pass : fail).push(value);
- });
- return [pass, fail];
- };
+ _.partition = group(function(result, value, pass) {
+ result[pass ? 0 : 1].push(value);
+ }, true);
-
-
-
+
+
+
- _.compact = function(obj) {
- return _.filter(obj, _.identity);
- };
-
-
-
-
-
-
- ¶
-
- Array Functions
-
-
-
-
-
-
-
+
@@ -1087,11 +1133,11 @@ Array Functions
-
+
Get the first element of an array. Passing n will return the first N
values in the array. Aliased as head
and take
. The guard check
@@ -1099,8 +1145,8 @@
Array Functions
- _.first = _.head = _.take = function(array, n, guard) {
- if (array == null) return void 0;
+ _.first = _.head = _.take = function(array, n, guard) {
+ if (array == null || array.length < 1) return void 0;
if (n == null || guard) return array[0];
return _.initial(array, array.length - n);
};
@@ -1108,11 +1154,11 @@ Array Functions
-
+
Returns everything but the last entry of the array. Especially useful on
the arguments object. Passing n will return all the values in
@@ -1120,26 +1166,26 @@
Array Functions
- _.initial = function(array, n, guard) {
+ _.initial = function(array, n, guard) {
return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
};
-
+
- _.last = function(array, n, guard) {
- if (array == null) return void 0;
+ _.last = function(array, n, guard) {
+ if (array == null || array.length < 1) return void 0;
if (n == null || guard) return array[array.length - 1];
return _.rest(array, Math.max(0, array.length - n));
};
@@ -1147,11 +1193,11 @@ Array Functions
-
+
Returns everything but the first entry of the array. Aliased as tail
and drop
.
Especially useful on the arguments object. Passing an n will return
@@ -1159,47 +1205,66 @@
Array Functions
- _.rest = _.tail = _.drop = function(array, n, guard) {
+ _.rest = _.tail = _.drop = function(array, n, guard) {
return slice.call(array, n == null || guard ? 1 : n);
};
-
+
-
+
+
+ _.compact = function(array) {
+ return _.filter(array, Boolean);
+ };
+
+
+
+
+
+
+
+
+ ¶
Internal implementation of a recursive flatten
function.
- var flatten = function(input, shallow, strict, startIndex) {
- var output = [], idx = 0;
- for (var i = startIndex || 0, length = getLength(input); i < length; i++) {
+ var flatten = function(input, shallow, strict, output) {
+ output = output || [];
+ var idx = output.length;
+ for (var i = 0, length = getLength(input); i < length; i++) {
var value = input[i];
if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
-
+
- flatten current level of array or arguments object
+ Flatten current level of array or arguments object.
- if (!shallow) value = flatten(value, shallow, strict);
- var j = 0, len = value.length;
- output.length += len;
- while (j < len) {
- output[idx++] = value[j++];
+ if (shallow) {
+ var j = 0, len = value.length;
+ while (j < len) output[idx++] = value[j++];
+ } else {
+ flatten(value, shallow, strict, output);
+ idx = output.length;
}
} else if (!strict) {
output[idx++] = value;
@@ -1211,45 +1276,45 @@ Array Functions
-
+
- _.flatten = function(array, shallow) {
+ _.flatten = function(array, shallow) {
return flatten(array, shallow, false);
};
-
+
- _.without = function(array) {
- return _.difference(array, slice.call(arguments, 1));
- };
+ _.without = restArgs(function(array, otherArrays) {
+ return _.difference(array, otherArrays);
+ });
-
+
Produce a duplicate-free version of the array. If the array has already
been sorted, you have the option of using a faster algorithm.
@@ -1257,7 +1322,7 @@
Array Functions
- _.uniq = _.unique = function(array, isSorted, iteratee, context) {
+ _.uniq = _.unique = function(array, isSorted, iteratee, context) {
if (!_.isBoolean(isSorted)) {
context = iteratee;
iteratee = isSorted;
@@ -1287,42 +1352,43 @@ Array Functions
-
+
Produce an array that contains the union: each distinct element from all of
the passed-in arrays.
- _.union = function() {
- return _.uniq(flatten(arguments, true, true));
- };
+ _.union = restArgs(function(arrays) {
+ return _.uniq(flatten(arrays, true, true));
+ });
-
+
- _.intersection = function(array) {
+ _.intersection = function(array) {
var result = [];
var argsLength = arguments.length;
for (var i = 0, length = getLength(array); i < length; i++) {
var item = array[i];
if (_.contains(result, item)) continue;
- for (var j = 1; j < argsLength; j++) {
+ var j;
+ for (j = 1; j < argsLength; j++) {
if (!_.contains(arguments[j], item)) break;
}
if (j === argsLength) result.push(item);
@@ -1333,82 +1399,80 @@ Array Functions
-
+
Take the difference between one array and a number of other arrays.
Only the elements present in just the first array will remain.
- _.difference = function(array) {
- var rest = flatten(arguments, true, true, 1);
- return _.filter(array, function(value){
+ _.difference = restArgs(function(array, rest) {
+ rest = flatten(rest, true, true);
+ return _.filter(array, function(value){
return !_.contains(rest, value);
});
- };
+ });
-
+
- Zip together multiple lists into a single array — elements that share
-an index go together.
+ Complement of _.zip. Unzip accepts an array of arrays and groups
+each array’s elements on shared indices.
- _.zip = function() {
- return _.unzip(arguments);
+ _.unzip = function(array) {
+ var length = array && _.max(array, getLength).length || 0;
+ var result = Array(length);
+
+ for (var index = 0; index < length; index++) {
+ result[index] = _.pluck(array, index);
+ }
+ return result;
};
-
+
- Complement of _.zip. Unzip accepts an array of arrays and groups
-each array’s elements on shared indices
+ Zip together multiple lists into a single array – elements that share
+an index go together.
- _.unzip = function(array) {
- var length = array && _.max(array, getLength).length || 0;
- var result = Array(length);
-
- for (var index = 0; index < length; index++) {
- result[index] = _.pluck(array, index);
- }
- return result;
- };
+ _.zip = restArgs(_.unzip);
-
+
Converts lists into objects. Pass either a single array of [key, value]
-pairs, or two parallel arrays of the same length — one of keys, and one of
-the corresponding values.
+pairs, or two parallel arrays of the same length – one of keys, and one of
+the corresponding values. Passing by pairs is the reverse of _.pairs.
- _.object = function(list, values) {
+ _.object = function(list, values) {
var result = {};
for (var i = 0, length = getLength(list); i < length; i++) {
if (values) {
@@ -1423,59 +1487,59 @@ Array Functions
-
+
- Generator function to create the findIndex and findLastIndex functions
+ Generator function to create the findIndex and findLastIndex functions.
- function createPredicateIndexFinder(dir) {
- return function(array, predicate, context) {
+ var createPredicateIndexFinder = function(dir) {
+ return function(array, predicate, context) {
predicate = cb(predicate, context);
var length = getLength(array);
var index = dir > 0 ? 0 : length - 1;
for (; index >= 0 && index < length; index += dir) {
if (predicate(array[index], index, array)) return index;
}
- return -1;
+ return -1;
};
- }
+ };
-
+
- Returns the first index on an array-like that passes a predicate test
+ Returns the first index on an array-like that passes a predicate test.
_.findIndex = createPredicateIndexFinder(1);
- _.findLastIndex = createPredicateIndexFinder(-1);
+ _.findLastIndex = createPredicateIndexFinder(-1);
-
+
Use a comparator function to figure out the smallest index at which
an object should be inserted so as to maintain order. Uses binary search.
- _.sortedIndex = function(array, obj, iteratee, context) {
+ _.sortedIndex = function(array, obj, iteratee, context) {
iteratee = cb(iteratee, context, 1);
var value = iteratee(obj);
var low = 0, high = getLength(array);
@@ -1489,48 +1553,48 @@ Array Functions
-
+
- Generator function to create the indexOf and lastIndexOf functions
+ Generator function to create the indexOf and lastIndexOf functions.
- function createIndexFinder(dir, predicateFind, sortedIndex) {
- return function(array, item, idx) {
+ var createIndexFinder = function(dir, predicateFind, sortedIndex) {
+ return function(array, item, idx) {
var i = 0, length = getLength(array);
if (typeof idx == 'number') {
if (dir > 0) {
- i = idx >= 0 ? idx : Math.max(idx + length, i);
+ i = idx >= 0 ? idx : Math.max(idx + length, i);
} else {
- length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
+ length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
}
} else if (sortedIndex && idx && length) {
idx = sortedIndex(array, item);
- return array[idx] === item ? idx : -1;
+ return array[idx] === item ? idx : -1;
}
if (item !== item) {
idx = predicateFind(slice.call(array, i, length), _.isNaN);
- return idx >= 0 ? idx + i : -1;
+ return idx >= 0 ? idx + i : -1;
}
for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
if (array[idx] === item) return idx;
}
- return -1;
+ return -1;
};
- }
+ };
-
+
Return the position of the first occurrence of an item in an array,
or -1 if the item is not included in the array.
@@ -1540,16 +1604,16 @@
Array Functions
_.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
- _.lastIndexOf = createIndexFinder(-1, _.findLastIndex);
+ _.lastIndexOf = createIndexFinder(-1, _.findLastIndex);
-
+
Generate an integer Array containing an arithmetic progression. A port of
the native Python range()
function. See
@@ -1557,12 +1621,14 @@
Array Functions
- _.range = function(start, stop, step) {
+ _.range = function(start, stop, step) {
if (stop == null) {
stop = start || 0;
start = 0;
}
- step = step || 1;
+ if (!step) {
+ step = stop < start ? -1 : 1;
+ }
var length = Math.max(Math.ceil((stop - start) / step), 0);
var range = Array(length);
@@ -1577,11 +1643,36 @@ Array Functions
-
+
+ Split an array into several arrays containing count or less elements
+of initial array.
+
+
+
+ _.chunk = function(array, count) {
+ if (count == null || count < 1) return [];
+
+ var result = [];
+ var i = 0, length = array.length;
+ while (i < length) {
+ result.push(slice.call(array, i, i += count));
+ }
+ return result;
+ };
+
+
+
+
+
+
+
+
+ ¶
Function (ahem) Functions
@@ -1590,11 +1681,11 @@ Function (ahem) Functions
-
+
@@ -1602,18 +1693,18 @@ Function (ahem) Functions
-
+
Determines whether to execute a function as a constructor
-or a normal function with the provided arguments
+or a normal function with the provided arguments.
- var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {
+ var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {
if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
var self = baseCreate(sourceFunc.prototype);
var result = sourceFunc.apply(self, args);
@@ -1624,11 +1715,11 @@ Function (ahem) Functions
-
+
Create a function bound to a given object (assigning this
, and arguments,
optionally). Delegates to ECMAScript 5‘s native Function.bind
if
@@ -1636,53 +1727,54 @@
Function (ahem) Functions
- _.bind = function(func, context) {
- if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
+ _.bind = restArgs(function(func, context, args) {
if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
- var args = slice.call(arguments, 2);
- var bound = function() {
- return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));
- };
+ var bound = restArgs(function(callArgs) {
+ return executeBound(func, bound, context, this, args.concat(callArgs));
+ });
return bound;
- };
+ });
-
+
Partially apply a function by creating a version that has had some of its
-arguments pre-filled, without changing its dynamic this
context. _ acts
-as a placeholder, allowing any combination of arguments to be pre-filled.
+arguments pre-filled, without changing its dynamic this
context. acts
+as a placeholder by default, allowing any combination of arguments to be
+pre-filled. Set `.partial.placeholder` for a custom placeholder argument.
- _.partial = function(func) {
- var boundArgs = slice.call(arguments, 1);
- var bound = function() {
+ _.partial = restArgs(function(func, boundArgs) {
+ var placeholder = _.partial.placeholder;
+ var bound = function() {
var position = 0, length = boundArgs.length;
var args = Array(length);
for (var i = 0; i < length; i++) {
- args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];
+ args[i] = boundArgs[i] === placeholder ? arguments[position++] : boundArgs[i];
}
while (position < arguments.length) args.push(arguments[position++]);
return executeBound(func, bound, this, this, args);
};
return bound;
- };
+ });
+
+ _.partial.placeholder = _;
-
+
Bind a number of an object’s methods to that object. Remaining arguments
are the method names to be bound. Useful for ensuring that all callbacks
@@ -1690,31 +1782,31 @@
Function (ahem) Functions
- _.bindAll = function(obj) {
- var i, length = arguments.length, key;
- if (length <= 1) throw new Error('bindAll must be passed function names');
- for (i = 1; i < length; i++) {
- key = arguments[i];
+ _.bindAll = restArgs(function(obj, keys) {
+ keys = flatten(keys, false, false);
+ var index = keys.length;
+ if (index < 1) throw new Error('bindAll must be passed function names');
+ while (index--) {
+ var key = keys[index];
obj[key] = _.bind(obj[key], obj);
}
- return obj;
- };
+ });
-
+
- _.memoize = function(func, hasher) {
- var memoize = function(key) {
+ _.memoize = function(func, hasher) {
+ var memoize = function(key) {
var cache = memoize.cache;
var address = '' + (hasher ? hasher.apply(this, arguments) : key);
if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
@@ -1727,32 +1819,31 @@ Function (ahem) Functions
-
+
Delays a function for the given number of milliseconds, and then calls
it with the arguments supplied.
- _.delay = function(func, wait) {
- var args = slice.call(arguments, 2);
- return setTimeout(function(){
+ _.delay = restArgs(function(func, wait, args) {
+ return setTimeout(function() {
return func.apply(null, args);
}, wait);
- };
+ });
-
+
Defers a function, scheduling it to run after the current call stack has
cleared.
@@ -1764,11 +1855,11 @@ Function (ahem) Functions
-
+
Returns a function, that, when invoked, will only be triggered at most once
during a given window of time. Normally, the throttled function will run
@@ -1778,18 +1869,19 @@
Function (ahem) Functions
- _.throttle = function(func, wait, options) {
- var context, args, result;
- var timeout = null;
+ _.throttle = function(func, wait, options) {
+ var timeout, context, args, result;
var previous = 0;
if (!options) options = {};
- var later = function() {
+
+ var later = function() {
previous = options.leading === false ? 0 : _.now();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
- return function() {
+
+ var throttled = function() {
var now = _.now();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
@@ -1808,16 +1900,24 @@ Function (ahem) Functions
}
return result;
};
+
+ throttled.cancel = function() {
+ clearTimeout(timeout);
+ previous = 0;
+ timeout = context = args = null;
+ };
+
+ return throttled;
};
-
+
Returns a function, that, as long as it continues to be invoked, will not
be triggered. The function will be called after it stops being called for
@@ -1826,46 +1926,43 @@
Function (ahem) Functions
- _.debounce = function(func, wait, immediate) {
- var timeout, args, context, timestamp, result;
-
- var later = function() {
- var last = _.now() - timestamp;
+ _.debounce = function(func, wait, immediate) {
+ var timeout, result;
- if (last < wait && last >= 0) {
- timeout = setTimeout(later, wait - last);
- } else {
- timeout = null;
- if (!immediate) {
- result = func.apply(context, args);
- if (!timeout) context = args = null;
- }
- }
+ var later = function(context, args) {
+ timeout = null;
+ if (args) result = func.apply(context, args);
};
- return function() {
- context = this;
- args = arguments;
- timestamp = _.now();
- var callNow = immediate && !timeout;
- if (!timeout) timeout = setTimeout(later, wait);
- if (callNow) {
- result = func.apply(context, args);
- context = args = null;
+ var debounced = restArgs(function(args) {
+ if (timeout) clearTimeout(timeout);
+ if (immediate) {
+ var callNow = !timeout;
+ timeout = setTimeout(later, wait);
+ if (callNow) result = func.apply(this, args);
+ } else {
+ timeout = _.delay(later, wait, this, args);
}
return result;
+ });
+
+ debounced.cancel = function() {
+ clearTimeout(timeout);
+ timeout = null;
};
+
+ return debounced;
};
-
+
Returns the first function passed as an argument to the second,
allowing you to adjust arguments, run code before and after, and
@@ -1873,25 +1970,25 @@
Function (ahem) Functions
- _.wrap = function(func, wrapper) {
+ _.wrap = function(func, wrapper) {
return _.partial(wrapper, func);
};
-
+
- _.negate = function(predicate) {
- return function() {
+ _.negate = function(predicate) {
+ return function() {
return !predicate.apply(this, arguments);
};
};
@@ -1899,21 +1996,21 @@ Function (ahem) Functions
-
+
Returns a function that is the composition of a list of functions, each
consuming the return value of the function that follows.
- _.compose = function() {
+ _.compose = function() {
var args = arguments;
var start = args.length - 1;
- return function() {
+ return function() {
var i = start;
var result = args[start].apply(this, arguments);
while (i--) result = args[i].call(this, result);
@@ -1924,18 +2021,18 @@ Function (ahem) Functions
-
+
- _.after = function(times, func) {
- return function() {
+ _.after = function(times, func) {
+ return function() {
if (--times < 1) {
return func.apply(this, arguments);
}
@@ -1945,19 +2042,19 @@ Function (ahem) Functions
-
+
- _.before = function(times, func) {
+ _.before = function(times, func) {
var memo;
- return function() {
+ return function() {
if (--times > 0) {
memo = func.apply(this, arguments);
}
@@ -1969,27 +2066,29 @@ Function (ahem) Functions
-
+
Returns a function that will be executed at most one time, no matter how
often you call it. Useful for lazy initialization.
- _.once = _.partial(_.before, 2);
+ _.once = _.partial(_.before, 2);
+
+ _.restArgs = restArgs;
-
+
Object Functions
@@ -1998,11 +2097,11 @@ Object Functions
-
+
@@ -2010,33 +2109,33 @@ Object Functions
-
+
- var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
+ var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
- function collectNonEnumProps(obj, keys) {
+ var collectNonEnumProps = function(obj, keys) {
var nonEnumIdx = nonEnumerableProps.length;
- var constructor = obj.constructor;
- var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto;
+ var constructor = obj.constructor;
+ var proto = _.isFunction(constructor) && constructor.prototype || ObjProto;
-
+
+ };
-
+
Retrieve the names of an object’s own properties.
-Delegates to ECMAScript 5‘s native Object.keys
+Delegates to ECMAScript 5‘s native Object.keys
.
- _.keys = function(obj) {
+ _.keys = function(obj) {
if (!_.isObject(obj)) return [];
if (nativeKeys) return nativeKeys(obj);
var keys = [];
@@ -2076,11 +2175,11 @@ Object Functions
-
+
Ahem, IE < 9.
@@ -2093,17 +2192,17 @@ Object Functions
-
+
- _.allKeys = function(obj) {
+ _.allKeys = function(obj) {
if (!_.isObject(obj)) return [];
var keys = [];
for (var key in obj) keys.push(key);
@@ -2111,11 +2210,11 @@ Object Functions
-
+
Ahem, IE < 9.
@@ -2128,17 +2227,17 @@ Object Functions
-
+
- _.values = function(obj) {
+ _.values = function(obj) {
var keys = _.keys(obj);
var length = keys.length;
var values = Array(length);
@@ -2151,44 +2250,44 @@ Object Functions
-
+
- Returns the results of applying the iteratee to each element of the object
-In contrast to _.map it returns an object
+ Returns the results of applying the iteratee to each element of the object.
+In contrast to _.map it returns an object.
- _.mapObject = function(obj, iteratee, context) {
+ _.mapObject = function(obj, iteratee, context) {
iteratee = cb(iteratee, context);
- var keys = _.keys(obj),
- length = keys.length,
- results = {},
- currentKey;
- for (var index = 0; index < length; index++) {
- currentKey = keys[index];
- results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
- }
- return results;
+ var keys = _.keys(obj),
+ length = keys.length,
+ results = {};
+ for (var index = 0; index < length; index++) {
+ var currentKey = keys[index];
+ results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
+ }
+ return results;
};
-
+
- Convert an object into a list of [key, value]
pairs.
+ Convert an object into a list of [key, value]
pairs.
+The opposite of _.object.
- _.pairs = function(obj) {
+ _.pairs = function(obj) {
var keys = _.keys(obj);
var length = keys.length;
var pairs = Array(length);
@@ -2201,17 +2300,17 @@ Object Functions
-
+
- _.invert = function(obj) {
+ _.invert = function(obj) {
var result = {};
var keys = _.keys(obj);
for (var i = 0, length = keys.length; i < length; i++) {
@@ -2223,18 +2322,18 @@ Object Functions
-
+
Return a sorted list of the function names available on the object.
-Aliased as methods
+Aliased as methods
.
- _.functions = _.methods = function(obj) {
+ _.functions = _.methods = function(obj) {
var names = [];
for (var key in obj) {
if (_.isFunction(obj[key])) names.push(key);
@@ -2245,11 +2344,42 @@ Object Functions
-
+
+
+ var createAssigner = function(keysFunc, defaults) {
+ return function(obj) {
+ var length = arguments.length;
+ if (defaults) obj = Object(obj);
+ if (length < 2 || obj == null) return obj;
+ for (var index = 1; index < length; index++) {
+ var source = arguments[index],
+ keys = keysFunc(source),
+ l = keys.length;
+ for (var i = 0; i < l; i++) {
+ var key = keys[i];
+ if (!defaults || obj[key] === void 0) obj[key] = source[key];
+ }
+ }
+ return obj;
+ };
+ };
+
+
+
+
+
+
+
+
+ ¶
Extend a given object with all the properties in passed-in object(s).
@@ -2260,13 +2390,13 @@ Object Functions
-
+
- Assigns a given object with all the own properties in the passed-in object(s)
+
Assigns a given object with all the own properties in the passed-in object(s).
(https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
@@ -2276,17 +2406,17 @@ Object Functions
-
+
- Returns the first key on an object that passes a predicate test
+ Returns the first key on an object that passes a predicate test.
- _.findKey = function(obj, predicate, context) {
+