diff --git a/README.md b/README.md index d404834774..923745b83d 100644 --- a/README.md +++ b/README.md @@ -1,17 +1,25 @@ -# Lo-Dash v0.10.0 +# Lo-Dash v1.0.0-rc.1 [![build status](https://secure.travis-ci.org/bestiejs/lodash.png)](http://travis-ci.org/bestiejs/lodash) -A drop-in replacement[*](https://github.com/bestiejs/lodash/wiki/Drop-in-Disclaimer) for Underscore.js, from the devs behind [jsPerf.com](http://jsperf.com), delivering [performance](http://lodash.com/benchmarks), [bug fixes](https://github.com/bestiejs/lodash#resolved-underscorejs-issues), and [additional features](http://lodash.com/#features). - -Lo-Dash’s performance is gained by avoiding slower native methods, instead opting for simplified non-ES5 compliant methods optimized for common usage, and by leveraging function compilation to reduce the number of overall function calls. +A utility library, usable as a drop-in replacement for Underscore, delivering [performance](http://lodash.com/benchmarks), [bug fixes](https://github.com/bestiejs/lodash#resolved-underscorejs-issues), and [additional features](http://lodash.com/#features). ## Download - * [Development build](https://raw.github.com/bestiejs/lodash/v0.10.0/lodash.js) - * [Production build](https://raw.github.com/bestiejs/lodash/v0.10.0/lodash.min.js) - * [Underscore build](https://raw.github.com/bestiejs/lodash/v0.10.0/lodash.underscore.min.js) tailored for projects already using Underscore - * CDN copies of ≤ v0.10.0’s [Production](http://cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js), [Underscore](http://cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.underscore.min.js), and [Development](http://cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.js) builds are available on [cdnjs](http://cdnjs.com/) thanks to [CloudFlare](http://www.cloudflare.com/) - * For optimal file size, [create a custom build](https://github.com/bestiejs/lodash#custom-builds) with only the features you need +* Lo-Dash builds:
+[Development](https://raw.github.com/bestiejs/lodash/v1.0.0-rc.1/lodash.js) and +[Production](https://raw.github.com/bestiejs/lodash/v1.0.0-rc.1/lodash.min.js) + +* Underscore builds:
+[Development](https://raw.github.com/bestiejs/lodash/v1.0.0-rc.1/lodash.underscore.js) and +[Production](https://raw.github.com/bestiejs/lodash/v1.0.0-rc.1/lodash.underscore.min.js) + +* CDN copies of ≤ v1.0.0-rc.1’s builds are available on [cdnjs](http://cdnjs.com/) thanks to [CloudFlare](http://www.cloudflare.com/):
+[Lo-Dash development](http://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.0.0-rc.1/lodash.js), +[Lo-Dash production](http://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.0.0-rc.1/lodash.min.js), +[Underscore development](http://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.0.0-rc.1/lodash.underscore.js), and +[Underscore production](http://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.0.0-rc.1/lodash.underscore.min.js) + +* For optimal file size, [create a custom build](https://github.com/bestiejs/lodash#custom-builds) with only the features you need ## Dive in @@ -35,23 +43,23 @@ For more information check out these screencasts over Lo-Dash: ## Features * AMD loader support ([RequireJS](http://requirejs.org/), [curl.js](https://github.com/cujojs/curl), etc.) + * [_.bindKey](http://lodash.com/docs#bindKey) for binding [*“lazy”* defined](http://michaux.ca/articles/lazy-function-definition-pattern) methods * [_.clone](http://lodash.com/docs#clone) supports *“deep”* cloning * [_.contains](http://lodash.com/docs#contains) accepts a `fromIndex` argument * [_.forEach](http://lodash.com/docs#forEach) is chainable and supports exiting iteration early * [_.forIn](http://lodash.com/docs#forIn) for iterating over an object’s own and inherited properties * [_.forOwn](http://lodash.com/docs#forOwn) for iterating over an object’s own properties * [_.isPlainObject](http://lodash.com/docs#isPlainObject) checks if values are created by the `Object` constructor - * [_.bindKey](http://lodash.com/docs#bindKey) for binding [*“lazy”* defined](http://michaux.ca/articles/lazy-function-definition-pattern) methods * [_.merge](http://lodash.com/docs#merge) for a *“deep”* [_.extend](http://lodash.com/docs#extend) * [_.partial](http://lodash.com/docs#partial) for partial application without `this` binding * [_.pick](http://lodash.com/docs#pick) and [_.omit](http://lodash.com/docs#omit) accepts `callback` and `thisArg` arguments - * [_.template](http://lodash.com/docs#template) supports [ES6 delimiters](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-7.8.6) and utilizes [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) for easier debugging + * [_.template](http://lodash.com/docs#template) supports [ES6 template delimiters](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-7.8.6) and utilizes [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) for easier debugging * [_.contains](http://lodash.com/docs#contains), [_.size](http://lodash.com/docs#size), [_.toArray](http://lodash.com/docs#toArray), [and more…](http://lodash.com/docs "_.countBy, _.every, _.filter, _.find, _.forEach, _.groupBy, _.invoke, _.map, _.max, _.min, _.pluck, _.reduce, _.reduceRight, _.reject, _.shuffle, _.some, _.sortBy, _.where") accept strings ## Support -Lo-Dash has been tested in at least Chrome 5~23, Firefox 1~16, IE 6-10, Opera 9.25-12, Safari 3-6, Node.js 0.4.8-0.8.14, Narwhal 0.3.2, RingoJS 0.8, and Rhino 1.7RC5. +Lo-Dash has been tested in at least Chrome 5~23, Firefox 1~16, IE 6-10, Opera 9.25-12, Safari 3-6, Node.js 0.4.8-0.8.15, Narwhal 0.3.2, RingoJS 0.8, and Rhino 1.7RC5. ## Custom builds @@ -185,9 +193,12 @@ In [Node.js](http://nodejs.org/) and [RingoJS v0.8.0+](http://ringojs.org/): ```js var _ = require('lodash'); + +// or as a drop-in replacement for Underscore +var _ = require('lodash/lodash.underscore'); ``` -**Note:** If Lo-Dash is installed globally, [run `npm link lodash`](http://blog.nodejs.org/2011/03/23/npm-1-0-global-vs-local-installation/) in your project’s root directory before requiring it. +**Note:** If Lo-Dash is installed globally, run [`npm link lodash`](http://blog.nodejs.org/2011/03/23/npm-1-0-global-vs-local-installation/) in your project’s root directory before requiring it. In [RingoJS v0.7.0-](http://ringojs.org/): @@ -216,34 +227,34 @@ require({ ## Resolved Underscore.js issues - * Allow iteration of objects with a `length` property [[#799](https://github.com/documentcloud/underscore/pull/799), [test](https://github.com/bestiejs/lodash/blob/v0.10.0/test/test.js#L590-L596)] - * Fix cross-browser object iteration bugs [[#60](https://github.com/documentcloud/underscore/issues/60), [#376](https://github.com/documentcloud/underscore/issues/376), [test](https://github.com/bestiejs/lodash/blob/v0.10.0/test/test.js#L603-L627)] - * Methods should work on pages with incorrectly shimmed native methods [[#7](https://github.com/documentcloud/underscore/issues/7), [#742](https://github.com/documentcloud/underscore/issues/742), [test](https://github.com/bestiejs/lodash/blob/v0.10.0/test/test.js#L140-L146)] - * `_.isEmpty` should support jQuery/MooTools DOM query collections [[#690](https://github.com/documentcloud/underscore/pull/690), [test](https://github.com/bestiejs/lodash/blob/v0.10.0/test/test.js#L792-L797)] - * `_.isObject` should avoid V8 bug [#2291](http://code.google.com/p/v8/issues/detail?id=2291) [[#605](https://github.com/documentcloud/underscore/issues/605), [test](https://github.com/bestiejs/lodash/blob/v0.10.0/test/test.js#L873-L885)] - * `_.keys` should work with `arguments` objects cross-browser [[#396](https://github.com/documentcloud/underscore/issues/396), [test](https://github.com/bestiejs/lodash/blob/v0.10.0/test/test.js#L966-L968)] - * `_.range` should coerce arguments to numbers [[#634](https://github.com/documentcloud/underscore/issues/634), [#683](https://github.com/documentcloud/underscore/issues/683), [test](https://github.com/bestiejs/lodash/blob/v0.10.0/test/test.js#L1367-L1370)] + * Allow iteration of objects with a `length` property [[#799](https://github.com/documentcloud/underscore/pull/799), [test](https://github.com/bestiejs/lodash/blob/v1.0.0-rc.1/test/test.js#L605-L611)] + * Fix cross-browser object iteration bugs [[#60](https://github.com/documentcloud/underscore/issues/60), [#376](https://github.com/documentcloud/underscore/issues/376), [test](https://github.com/bestiejs/lodash/blob/v1.0.0-rc.1/test/test.js#L618-L642)] + * Methods should work on pages with incorrectly shimmed native methods [[#7](https://github.com/documentcloud/underscore/issues/7), [#742](https://github.com/documentcloud/underscore/issues/742), [test](https://github.com/bestiejs/lodash/blob/v1.0.0-rc.1/test/test.js#L140-L146)] + * `_.isEmpty` should support jQuery/MooTools DOM query collections [[#690](https://github.com/documentcloud/underscore/pull/690), [test](https://github.com/bestiejs/lodash/blob/v1.0.0-rc.1/test/test.js#L807-L812)] + * `_.isObject` should avoid V8 bug [#2291](http://code.google.com/p/v8/issues/detail?id=2291) [[#605](https://github.com/documentcloud/underscore/issues/605), [test](https://github.com/bestiejs/lodash/blob/v1.0.0-rc.1/test/test.js#L888-L900)] + * `_.keys` should work with `arguments` objects cross-browser [[#396](https://github.com/documentcloud/underscore/issues/396), [test](https://github.com/bestiejs/lodash/blob/v1.0.0-rc.1/test/test.js#L981-L983)] + * `_.range` should coerce arguments to numbers [[#634](https://github.com/documentcloud/underscore/issues/634), [#683](https://github.com/documentcloud/underscore/issues/683), [test](https://github.com/bestiejs/lodash/blob/v1.0.0-rc.1/test/test.js#L1382-L1385)] ## Release Notes -### v0.10.0 +### v1.0.0-rc.1 #### Compatibility Warnings #### - * Aligned `_.defaults` and `_.extend` with ES6 [Object.assign](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-15.2.3.15) - * Renamed `_.lateBind` to `_.bindKey` + * Made `_(…)` chain automatically without needing to call `_#chain` + * Made `_.isEqual` equate `arguments` objects to similar `Object` objects + * Made `_.clone` copy the enumerable properties of `arguments` objects and objects
+ created by constructors other than `Object` are cloned to plain `Object` objects #### Changes #### - * Added the build commands used to custom build copyright/license headers - * Added `_.assign` - * Ensured the `underscore` build of `_.find` returns the first, not last, matched value - * Ensured `_defaults`, `_.extends`, and `_.merge` works with `_.reduce` - * Made Lo-Dash’s `npm` package installation work with more system configurations - * Made `_.extend` an alias of `_.assign` - * Optimized `_.contains`, `_.defaults`, `_.extend`, and `_.filter` - * Restricted `_.where` to iterate only own properties of the `source` object - * Updated `backbone` build Lo-Dash method dependencies + * Ensure Lo-Dash runs in the JS engine embedded in Adobe products + * Ensured `_.reduce` and `_.reduceRight` pass the correct number of `callback` arguments + * Ensured `_.throttle` nulls the `timeoutId` + * Made deep `_.clone` more closely follow the structured clone algorithm and copy array properties assigned by `RegExp#exec` + * Optimized compiled templates in Firefox + * Optimized `_.forEach`, `_.forOwn`, `_.isNumber`, and `_.isString` + * Simplified `iteratorTemplate` The full changelog is available [here](https://github.com/bestiejs/lodash/wiki/Changelog). diff --git a/build.js b/build.js index 23f060b436..7e507e933c 100755 --- a/build.js +++ b/build.js @@ -71,7 +71,7 @@ 'bindAll': ['bind', 'functions'], 'bindKey': ['isFunction', 'isObject'], 'chain': ['mixin'], - 'clone': ['assign', 'forEach', 'forOwn', 'isArguments', 'isObject', 'isPlainObject'], + 'clone': ['assign', 'forEach', 'forOwn', 'isArray', 'isObject'], 'compact': [], 'compose': [], 'contains': ['forEach', 'indexOf', 'isString'], @@ -87,7 +87,7 @@ 'find': ['forEach'], 'first': [], 'flatten': ['isArray'], - 'forEach': ['identity', 'isString'], + 'forEach': ['identity', 'isArguments', 'isString'], 'forIn': ['identity', 'isArguments'], 'forOwn': ['identity', 'isArguments'], 'functions': ['forIn', 'isFunction'], @@ -105,10 +105,10 @@ 'isDate': [], 'isElement': [], 'isEmpty': ['forOwn', 'isArguments', 'isFunction'], - 'isEqual': ['isArguments', 'isFunction'], + 'isEqual': ['forIn', 'isArguments', 'isFunction'], 'isFinite': [], 'isFunction': [], - 'isNaN': [], + 'isNaN': ['isNumber'], 'isNull': [], 'isNumber': [], 'isObject': [], @@ -124,7 +124,7 @@ 'memoize': [], 'merge': ['forOwn', 'isArray', 'isPlainObject'], 'min': ['forEach', 'isArray', 'isString'], - 'mixin': ['forEach', 'functions'], + 'mixin': ['filter', 'forEach', 'functions'], 'noConflict': [], 'object': [], 'omit': ['forIn', 'indexOf'], @@ -132,7 +132,7 @@ 'pairs': ['forOwn'], 'partial': ['isFunction', 'isObject'], 'pick': ['forIn'], - 'pluck': ['forEach'], + 'pluck': ['map'], 'random': [], 'range': [], 'reduce': ['forEach'], @@ -149,7 +149,7 @@ 'template': ['escape'], 'throttle': [], 'times': [], - 'toArray': ['values'], + 'toArray': ['isString', 'values'], 'unescape': [], 'union': ['uniq'], 'uniq': ['identity', 'indexOf'], @@ -263,7 +263,7 @@ * @returns {String} Returns the modified source. */ function addCommandsToHeader(source, commands) { - return source.replace(/(\/\*!\n)( \*)?( *Lo-Dash [0-9.]+)(.*)/, function() { + return source.replace(/(\/\*!\n)( \*)?( *Lo-Dash [\w.-]+)(.*)/, function() { // convert unmatched groups to empty strings var parts = _.map(slice.call(arguments, 1), function(part) { return part || ''; @@ -329,7 +329,7 @@ precompiled = getFunctionSource(_.template(text, null, options)), prop = filename.replace(/\..*$/, ''); - source.push(" templates['" + prop.replace(/'/g, "\\'") + "'] = " + precompiled + ';', ''); + source.push(" templates['" + prop.replace(/['\n\r\t]/g, '\\$&') + "'] = " + precompiled + ';', ''); } }); @@ -476,7 +476,7 @@ return []; } // recursively accumulate the dependencies of the `methodName` function, and - // the dependencies of its dependencies, and so on. + // the dependencies of its dependencies, and so on return _.uniq(dependencies.reduce(function(result, otherName) { result.push.apply(result, getDependencies(otherName).concat(otherName)); return result; @@ -524,6 +524,17 @@ return (source.match(/(?:\s*\/\/.*)*\n( *)if *\(isFunction\(\/x\/[\s\S]+?};\n\1}/) || [''])[0]; } + /** + * Gets the `iteratorTemplate` from `source`. + * + * @private + * @param {String} source The source to inspect. + * @returns {String} Returns the `iteratorTemplate`. + */ + function getIteratorTemplate(source) { + return (source.match(/^( *)var iteratorTemplate *= *[\s\S]+?\n\1.+?;\n/m) || [''])[0]; + } + /** * Gets the names of methods in `source` belonging to the given `category`. * @@ -626,6 +637,20 @@ return _.uniq(_.intersection(allMethods, methodNames)); } + /** + * Removes the `createFunction` function from `source`. + * + * @private + * @param {String} source The source to process. + * @returns {String} Returns the modified source. + */ + function removeCreateFunction(source) { + source = removeVar(source, 'isFirefox'); + return removeFunction(source, 'createFunction') + .replace(/createFunction/g, 'Function') + .replace(/(?:\s*\/\/.*)*\s*if *\(isIeOpera[^}]+}\n/, ''); + } + /** * Removes the all references to `refName` from `createIterator` in `source`. * @@ -652,13 +677,11 @@ * @private * @param {String} source The source to process. * @param {String} funcName The name of the function to remove. - * @returns {String} Returns the source with the function removed. + * @returns {String} Returns the modified source. */ function removeFunction(source, funcName) { - var modified, - snippet = matchFunction(source, funcName); - // remove function + var snippet = matchFunction(source, funcName); if (snippet) { source = source.replace(snippet, ''); } @@ -666,7 +689,7 @@ snippet = getMethodAssignments(source); // remove assignment and aliases - modified = getAliases(funcName).concat(funcName).reduce(function(result, otherName) { + var modified = getAliases(funcName).concat(funcName).reduce(function(result, otherName) { return result.replace(RegExp('(?:\\n *//.*\\s*)* *lodash\\.' + otherName + ' *= *.+\\n'), ''); }, snippet); @@ -681,7 +704,7 @@ * * @private * @param {String} source The source to process. - * @returns {String} Returns the source with the `isArguments` fallback removed. + * @returns {String} Returns the modified source. */ function removeIsArgumentsFallback(source) { return source.replace(getIsArgumentsFallback(source), ''); @@ -692,7 +715,7 @@ * * @private * @param {String} source The source to process. - * @returns {String} Returns the source with the `isFunction` fallback removed. + * @returns {String} Returns the modified source. */ function removeIsFunctionFallback(source) { return source.replace(getIsFunctionFallback(source), ''); @@ -706,11 +729,19 @@ * @returns {String} Returns the modified source. */ function removeKeysOptimization(source) { - return removeVar(source, 'isKeysFast') - // remove optimized branch in `iteratorTemplate` - .replace(/(?: *\/\/.*\n)* *'( *)<% *if *\(isKeysFast[\s\S]+?'\1<% *} *else *\{ *%>.+\n([\s\S]+?) *'\1<% *} *%>.+/, "'\\n' +\n$2") - // remove data object property assignment in `createIterator` - .replace(/ *'isKeysFast':.+\n/, ''); + source = removeVar(source, 'isKeysFast'); + + // remove optimized branch in `iteratorTemplate` + source = source.replace(getIteratorTemplate(source), function(match) { + return match.replace(/(?: *\/\/.*\n)* *["']( *)<% *if *\(isKeysFast[\s\S]+?["']\1<% *} *else *\{ *%>.+\n([\s\S]+?) *["']\1<% *} *%>.+/, "'\\n' +\n$2"); + }); + + // remove data object property assignment in `createIterator` + source = source.replace(matchFunction(source, 'createIterator'), function(match) { + return match.replace(/ *'isKeysFast':.+\n/, ''); + }); + + return source; } /** @@ -721,11 +752,19 @@ * @returns {String} Returns the modified source. */ function removeNoArgsClass(source) { - return removeVar(source, 'noArgsClass') - // remove `noArgsClass` from `_.clone` and `_.isEqual` - .replace(/ *\|\| *\(noArgsClass *&&[^)]+?\)\)/g, '') - // remove `noArgsClass` from `_.isEqual` - .replace(/if *\(noArgsClass[^}]+?}\n/, '\n'); + source = removeVar(source, 'noArgsClass'); + + // remove `noArgsClass` from `_.isEmpty` + source = source.replace(matchFunction(source, 'isEmpty'), function(match) { + return match.replace(/ *\|\| *\(noArgsClass *&&[^)]+?\)\)/g, ''); + }); + + // remove `noArgsClass` from `_.isEqual` + source = source.replace(matchFunction(source, 'isEqual'), function(match) { + return match.replace(/noArgsClass[^:]+:\s*/g, ''); + }); + + return source; } /** @@ -736,13 +775,25 @@ * @returns {String} Returns the modified source. */ function removeNoNodeClass(source) { - return source - // remove `noNodeClass` assignment - .replace(/(?:\n +\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/)?\n *try *\{(?:\s*\/\/.*)*\n *var noNodeClass[\s\S]+?catch[^}]+}\n/, '') - // remove `noNodeClass` from `isPlainObject` - .replace(/\(!noNodeClass *\|\|[\s\S]+?\)\) *&&/, '') - // remove `noNodeClass` from `_.isEqual` - .replace(/ *\|\| *\(noNodeClass *&&[\s\S]+?\)\)\)/, ''); + // remove `noNodeClass` assignment + source = source.replace(/(?:\n +\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/)?\n *try *\{(?:\s*\/\/.*)*\n *var noNodeClass[\s\S]+?catch[^}]+}\n/, ''); + + // remove `noNodeClass` from `shimIsPlainObject` + source = source.replace(matchFunction(source, 'shimIsPlainObject'), function(match) { + return match.replace(/ *&& *\(!noNodeClass[\s\S]+?\)\)/, ''); + }); + + // remove `noNodeClass` from `_.clone` + source = source.replace(matchFunction(source, 'clone'), function(match) { + return match.replace(/ *\|\| *\(noNodeClass[\s\S]+?\)\)/, ''); + }); + + // remove `noNodeClass` from `_.isEqual` + source = source.replace(matchFunction(source, 'isEqual'), function(match) { + return match.replace(/ *\|\| *\(noNodeClass[\s\S]+?\)\)\)/, ''); + }); + + return source; } /** @@ -751,16 +802,12 @@ * @private * @param {String} source The source to process. * @param {String} varName The name of the variable to remove. - * @returns {String} Returns the source with the variable removed. + * @returns {String} Returns the modified source. */ function removeVar(source, varName) { - // simplify `cloneableClasses` - if (varName == 'cloneableClasses') { - source = source.replace(/(var cloneableClasses *=)[\s\S]+?(true;\n)/, '$1$2'); - } - // simplify `hasObjectSpliceBug` - if (varName == 'hasObjectSpliceBug') { - source = source.replace(/(var hasObjectSpliceBug *=)[^;]+/, '$1false'); + // simplify `cloneableClasses`, `ctorByClass`, or `hasObjectSpliceBug` + if (/^(?:cloneableClasses|ctorByClass|hasObjectSpliceBug)$/.test(varName)) { + source = source.replace(RegExp('(var ' + varName + ' *=)[\\s\\S]+?\\n\\n'), '$1=null;\n\n'); } source = source.replace(RegExp( // match multi-line comment block @@ -777,35 +824,57 @@ // remove a variable at the end of a variable declaration list source = source.replace(RegExp(',\\s*' + varName + ' *=.+?;'), ';'); - // remove variable reference from `cloneableClasses` assignments - source = source.replace(RegExp('cloneableClasses\\[' + varName + '\\] *= *(?:false|true)?', 'g'), ''); - return removeFromCreateIterator(source, varName); } /** - * Searches `source` for a `varName` variable declaration and replaces its - * assigned value with `varValue`. + * Replaces the `funcName` function body in `source` with `funcValue`. + * + * @private + * @param {String} source The source to inspect. + * @param {String} varName The name of the function to replace. + * @returns {String} Returns the modified source. + */ + function replaceFunction(source, funcName, funcValue) { + var match = matchFunction(source, funcName); + if (match) { + // clip snippet after the JSDoc comment block + match = match.replace(/^\s*(?:\/\/.*|\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/)\n/, ''); + source = source.replace(match, function() { + return funcValue; + }); + } + return source; + } + + /** + * Replaces the `varName` variable declaration value in `source` with `varValue`. * * @private * @param {String} source The source to inspect. * @param {String} varName The name of the variable to replace. - * @returns {String} Returns the source with the variable replaced. + * @returns {String} Returns the modified source. */ function replaceVar(source, varName, varValue) { // replace a variable that's not part of a declaration list var result = source.replace(RegExp( '(( *)var ' + varName + ' *= *)' + '(?:.+?;|(?:Function\\(.+?|.*?[^,])\\n[\\s\\S]+?\\n\\2.+?;)\\n' - ), '$1' + varValue + ';\n'); + ), function(match, captured) { + return captured + varValue + ';\n'; + }); if (source == result) { // replace a varaible at the start or middle of a declaration list - result = source.replace(RegExp('((?:var|\\n) +' + varName + ' *=).+?,'), '$1 ' + varValue + ','); + result = source.replace(RegExp('((?:var|\\n) +' + varName + ' *=).+?,'), function(match, captured) { + return captured + ' ' + varValue + ','; + }); } if (source == result) { // replace a variable at the end of a variable declaration list - result = source.replace(RegExp('(,\\s*' + varName + ' *=).+?;'), '$1 ' + varValue + ';'); + result = source.replace(RegExp('(,\\s*' + varName + ' *=).+?;'), function(match, captured) { + return captured + ' ' + varValue + ';'; + }); } return result; } @@ -823,8 +892,12 @@ if (value) { source = source.replace(/^[\s\S]*?function[^{]+{/, "$&\n 'use strict';"); } - // replace `useStrict` branch in `value` with hard-coded option - return source.replace(/(?: *\/\/.*\n)*(\s*)' *<%.+?useStrict.+/, value ? "$1'\\'use strict\\';\\n' +" : ''); + // replace `useStrict` branch in `iteratorTemplate` with hard-coded option + source = source.replace(getIteratorTemplate(source), function(match) { + return match.replace(/(?: *\/\/.*\n)*(\s*)["'] *<%.+?useStrict.+/, value ? '$1"\'use strict\';\\n" +' : ''); + }); + + return source; } /*--------------------------------------------------------------------------*/ @@ -855,6 +928,7 @@ 'csp', 'legacy', 'mobile', + 'modularize', 'strict', 'underscore', '-c', '--stdout', @@ -926,6 +1000,9 @@ // flag used to specify a mobile build var isMobile = !isLegacy && (isCSP || isUnderscore || options.indexOf('mobile') > -1); + // flag used to specify a modularize build + var isModularize = options.indexOf('modularize') > -1; + // flag used to specify writing output to standard output var isStdOut = options.indexOf('-c') > -1 || options.indexOf('--stdout') > -1; @@ -1098,24 +1175,52 @@ else if (isUnderscore) { // remove unneeded variables source = removeVar(source, 'cloneableClasses'); + source = removeVar(source, 'ctorByClass'); // remove large array optimizations source = removeFunction(source, 'cachedContains'); source = removeVar(source, 'largeArraySize'); + // replace `_.assign` + source = replaceFunction(source, 'assign', [ + ' function assign(object) {', + ' if (!object) {', + ' return object;', + ' }', + ' for (var argsIndex = 1, argsLength = arguments.length; argsIndex < argsLength; argsIndex++) {', + ' var iteratee = arguments[argsIndex];', + ' if (iteratee) {', + ' for (var key in iteratee) {', + ' object[key] = iteratee[key];', + ' }', + ' }', + ' }', + ' return object;', + ' }' + ].join('\n')); + + // replace `_.chain` + source = replaceFunction(source, 'chain', [ + ' function chain(value) {', + ' value = new lodash(value);', + ' value.__chain__ = true;', + ' return value;', + ' }' + ].join('\n')); + // replace `_.clone` if (useUnderscoreClone) { - source = source.replace(/^( *)function clone[\s\S]+?\n\1}/m, [ + source = replaceFunction(source, 'clone', [ ' function clone(value) {', ' return value && objectTypes[typeof value]', - ' ? (isArray(value) ? slice.call(value) : assign({}, value))', + ' ? (isArray(value) ? slice(value) : assign({}, value))', ' : value', ' }' ].join('\n')); } // replace `_.contains` - source = source.replace(/^( *)function contains[\s\S]+?\n\1}/m, [ + source = replaceFunction(source, 'contains', [ ' function contains(collection, target) {', ' var length = collection ? collection.length : 0,', ' result = false;', @@ -1130,44 +1235,8 @@ ' }' ].join('\n')); - // replace `_.difference` - source = source.replace(/^( *)function difference[\s\S]+?\n\1}/m, [ - ' function difference(array) {', - ' var index = -1,', - ' length = array.length,', - ' flattened = concat.apply(arrayRef, arguments),', - ' result = [];', - '', - ' while (++index < length) {', - ' var value = array[index]', - ' if (indexOf(flattened, value, length) < 0) {', - ' result.push(value);', - ' }', - ' }', - ' return result', - ' }' - ].join('\n')); - - // replace `_.assign` - source = source.replace(/^( *)var assign *= *createIterator[\s\S]+?\);/m, [ - ' function assign(object) {', - ' if (!object) {', - ' return object;', - ' }', - ' for (var argsIndex = 1, argsLength = arguments.length; argsIndex < argsLength; argsIndex++) {', - ' var iteratee = arguments[argsIndex];', - ' if (iteratee) {', - ' for (var key in iteratee) {', - ' object[key] = iteratee[key];', - ' }', - ' }', - ' }', - ' return object;', - ' }' - ].join('\n')); - // replace `_.defaults` - source = source.replace(/^( *)var defaults *= *createIterator[\s\S]+?\);/m, [ + source = replaceFunction(source, 'defaults', [ ' function defaults(object) {', ' if (!object) {', ' return object;', @@ -1186,8 +1255,26 @@ ' }' ].join('\n')); + // replace `_.difference` + source = replaceFunction(source, 'difference', [ + ' function difference(array) {', + ' var index = -1,', + ' length = array.length,', + ' flattened = concat.apply(arrayRef, arguments),', + ' result = [];', + '', + ' while (++index < length) {', + ' var value = array[index]', + ' if (indexOf(flattened, value, length) < 0) {', + ' result.push(value);', + ' }', + ' }', + ' return result', + ' }' + ].join('\n')); + // replace `_.intersection` - source = source.replace(/^( *)function intersection[\s\S]+?\n\1}/m, [ + source = replaceFunction(source, 'intersection', [ ' function intersection(array) {', ' var args = arguments,', ' argsLength = args.length,', @@ -1209,7 +1296,7 @@ ].join('\n')); // replace `_.isEmpty` - source = source.replace(/^( *)function isEmpty[\s\S]+?\n\1}/m, [ + source = replaceFunction(source, 'isEmpty', [ ' function isEmpty(value) {', ' if (!value) {', ' return true;', @@ -1227,14 +1314,14 @@ ].join('\n')); // replace `_.isFinite` - source = source.replace(/^( *)function isFinite[\s\S]+?\n\1}/m, [ + source = replaceFunction(source, 'isFinite', [ ' function isFinite(value) {', ' return nativeIsFinite(value) && toString.call(value) == numberClass;', ' }' ].join('\n')); // replace `_.omit` - source = source.replace(/^( *)function omit[\s\S]+?\n\1}/m, [ + source = replaceFunction(source, 'omit', [ ' function omit(object) {', ' var props = concat.apply(arrayRef, arguments),', ' result = {};', @@ -1249,7 +1336,7 @@ ].join('\n')); // replace `_.pick` - source = source.replace(/^( *)function pick[\s\S]+?\n\1}/m, [ + source = replaceFunction(source, 'pick', [ ' function pick(object) {', ' var index = 0,', ' props = concat.apply(arrayRef, arguments),', @@ -1267,60 +1354,58 @@ ].join('\n')); // replace `_.template` - source = source.replace(/^( *)function template[\s\S]+?\n\1}/m, function() { - return [ - ' function template(text, data, options) {', - " text || (text = '');", - ' options = defaults({}, options, lodash.templateSettings);', - '', - ' var index = 0,', - ' source = "__p += \'",', - ' variable = options.variable;', - '', - ' var reDelimiters = RegExp(', - " (options.escape || reNoMatch).source + '|' +", - " (options.interpolate || reNoMatch).source + '|' +", - " (options.evaluate || reNoMatch).source + '|$'", - " , 'g');", - '', - ' text.replace(reDelimiters, function(match, escapeValue, interpolateValue, evaluateValue, offset) {', - ' source += text.slice(index, offset).replace(reUnescapedString, escapeStringChar);', - ' source +=', - ' escapeValue ? "\' +\\n_.escape(" + escapeValue + ") +\\n\'" :', - ' evaluateValue ? "\';\\n" + evaluateValue + ";\\n__p += \'" :', - ' interpolateValue ? "\' +\\n((__t = (" + interpolateValue + ")) == null ? \'\' : __t) +\\n\'" : \'\';', - '', - ' index = offset + match.length;', - ' });', - '', - ' source += "\';\\n";', - ' if (!variable) {', - " variable = 'obj';", - " source = 'with (' + variable + ' || {}) {\\n' + source + '\\n}\\n';", - ' }', - " source = 'function(' + variable + ') {\\n' +", - " 'var __t, __p = \\'\\', __j = Array.prototype.join;\\n' +", - " 'function print() { __p += __j.call(arguments, \\'\\') }\\n' +", - ' source +', - " 'return __p\\n}';", - '', - ' try {', - " var result = Function('_', 'return ' + source)(lodash);", - ' } catch(e) {', - ' e.source = source;', - ' throw e;', - ' }', - ' if (data) {', - ' return result(data);', - ' }', - ' result.source = source;', - ' return result;', - ' }' - ].join('\n'); - }); + source = replaceFunction(source, 'template', [ + ' function template(text, data, options) {', + " text || (text = '');", + ' options = defaults({}, options, lodash.templateSettings);', + '', + ' var index = 0,', + ' source = "__p += \'",', + ' variable = options.variable;', + '', + ' var reDelimiters = RegExp(', + " (options.escape || reNoMatch).source + '|' +", + " (options.interpolate || reNoMatch).source + '|' +", + " (options.evaluate || reNoMatch).source + '|$'", + " , 'g');", + '', + ' text.replace(reDelimiters, function(match, escapeValue, interpolateValue, evaluateValue, offset) {', + ' source += text.slice(index, offset).replace(reUnescapedString, escapeStringChar);', + ' source +=', + ' escapeValue ? "\' +\\n_.escape(" + escapeValue + ") +\\n\'" :', + ' evaluateValue ? "\';\\n" + evaluateValue + ";\\n__p += \'" :', + ' interpolateValue ? "\' +\\n((__t = (" + interpolateValue + ")) == null ? \'\' : __t) +\\n\'" : \'\';', + '', + ' index = offset + match.length;', + ' });', + '', + ' source += "\';\\n";', + ' if (!variable) {', + " variable = 'obj';", + " source = 'with (' + variable + ' || {}) {\\n' + source + '\\n}\\n';", + ' }', + " source = 'function(' + variable + ') {\\n' +", + ' "var __t, __p = \'\', __j = Array.prototype.join;\\n" +', + ' "function print() { __p += __j.call(arguments, \'\') }\\n" +', + ' source +', + " 'return __p\\n}';", + '', + ' try {', + " var result = Function('_', 'return ' + source)(lodash);", + ' } catch(e) {', + ' e.source = source;', + ' throw e;', + ' }', + ' if (data) {', + ' return result(data);', + ' }', + ' result.source = source;', + ' return result;', + ' }' + ].join('\n')); // replace `_.uniq` - source = source.replace(/^( *)function uniq[\s\S]+?\n\1}/m, [ + source = replaceFunction(source, 'uniq', [ ' function uniq(array, isSorted, callback, thisArg) {', ' var index = -1,', ' length = array ? array.length : 0,', @@ -1349,8 +1434,16 @@ ' }' ].join('\n')); + // replace `_.uniqueId` + source = replaceFunction(source, 'uniqueId', [ + ' function uniqueId(prefix) {', + ' var id = idCounter++;', + ' return prefix ? prefix + id : id;', + ' }' + ].join('\n')); + // replace `_.without` - source = source.replace(/^( *)function without[\s\S]+?\n\1}/m, [ + source = replaceFunction(source, 'without', [ ' function without(array) {', ' var index = -1,', ' length = array.length,', @@ -1366,21 +1459,47 @@ ' }' ].join('\n')); - // remove unneeded template related variables - source = removeVar(source, 'reComplexDelimiter'); - source = removeVar(source, 'reEmptyStringLeading'); - source = removeVar(source, 'reEmptyStringMiddle'); - source = removeVar(source, 'reEmptyStringTrailing'); - source = removeVar(source, 'reInsertVariable'); + // replace `wrapperChain` + source = replaceFunction(source, 'wrapperChain', [ + ' function wrapperChain() {', + ' this.__chain__ = true;', + ' return this;', + ' }' + ].join('\n')); + + // add `__chain__` checks to `_.mixin` and Array function wrappers + source = source.replace(/^( *)forEach\([\s\S]+?\n\1}.+/gm, function(match) { + return match.replace(/^( *)return new lodash\(([^)]+)\).+/m, function(submatch, indent, varName) { + return indent + [ + 'if (this.__chain__) {', + ' varName = new lodash(varName);', + ' varName.__chain__ = true;', + '}', + 'return varName;' + ].join('\n' + indent) + .replace(/varName/g, varName); + }); + }); // remove `arguments` object check from `_.isEqual` - source = source.replace(/ *\|\| *className *== *argsClass/, ''); - - // simplify DOM node check from `_.isEqual` - source = source.replace(/(if *\(className *!= *objectClass).+?noNodeClass[\s\S]+?{/, '$1) {'); + source = source.replace(matchFunction(source, 'isEqual'), function(match) { + return match.replace(/^ *if *\(.+== argsClass[^}]+}\n/gm, '') + }); // remove conditional `charCodeCallback` use from `_.max` and `_.min` - source = source.replace(/!callback *&& *isString\(collection\)[\s\S]+?: */g, ''); + _.each(['max', 'min'], function(methodName) { + source = source.replace(matchFunction(source, methodName), function(match) { + return match.replace(/!callback *&& *isString\(collection\)[\s\S]+?: */g, ''); + }); + }); + + // remove `lodash.prototype.toString` and `lodash.prototype.valueOf` assignments + source = source.replace(/ *lodash\.prototype\.(?:toString|valueOf) *=.+\n/g, ''); + + // remove `lodash.prototype` batch method assignments + source = source + .replace(/(?:\s*\/\/.*)*\n( *)forEach\(\['first'[\s\S]+?\n\1}.+/, '') + .replace(/(?:\s*\/\/.*)*\n( *)forEach\(filter[\s\S]+?lodash\.[\s\S]+?\n\1}.+/, ''); // remove unused features from `createBound` if (buildMethods.indexOf('partial') == -1) { @@ -1394,14 +1513,19 @@ if (isMobile) { source = replaceVar(source, 'isKeysFast', 'false'); source = removeKeysOptimization(source); + source = removeNoNodeClass(source); // remove `prototype` [[Enumerable]] fix from `_.keys` - source = source.replace(/(?:\s*\/\/.*)*(\s*return *).+?propertyIsEnumerable[\s\S]+?: */, '$1'); + source = source.replace(matchFunction(source, 'keys'), function(match) { + return match.replace(/(?:\s*\/\/.*)*(\s*return *).+?propertyIsEnumerable[\s\S]+?: */, '$1'); + }); // remove `prototype` [[Enumerable]] fix from `iteratorTemplate` - source = source - .replace(/(?: *\/\/.*\n)* *' *(?:<% *)?if *\(!hasDontEnumBug *(?:&&|\))[\s\S]+?<% *} *(?:%>|').+/g, '') - .replace(/!hasDontEnumBug *\|\|/g, ''); + source = source.replace(getIteratorTemplate(source), function(match) { + return match + .replace(/(?: *\/\/.*\n)* *["'] *(?:<% *)?if *\(!hasDontEnumBug *(?:&&|\))[\s\S]+?<% *} *(?:%>|["']).+/g, '') + .replace(/!hasDontEnumBug *\|\|/g, ''); + }); } vm.runInContext(source, context); return context._; @@ -1438,23 +1562,18 @@ /*----------------------------------------------------------------------*/ if (isLegacy) { - _.each(['isBindFast', 'nativeBind', 'nativeIsArray', 'nativeKeys'], function(varName) { + _.each(['isBindFast', 'isV8', 'nativeBind', 'nativeIsArray', 'nativeKeys', 'reNative'], function(varName) { source = removeVar(source, varName); }); - _.each(['bind', 'isArray'], function(methodName) { - var snippet = matchFunction(source, methodName), - modified = snippet; + // remove native `Function#bind` branch in `_.bind` + source = source.replace(matchFunction(source, 'bind'), function(match) { + return match.replace(/(?:\s*\/\/.*)*\s*return isBindFast[^:]+:\s*/, 'return '); + }); - // remove native `Function#bind` branch in `_.bind` - if (methodName == 'bind') { - modified = modified.replace(/(?:\s*\/\/.*)*\s*return isBindFast[^:]+:\s*/, 'return '); - } - // remove native `Array.isArray` branch in `_.isArray` - else { - modified = modified.replace(/nativeIsArray * \|\|/, ''); - } - source = source.replace(snippet, modified); + // remove native `Array.isArray` branch in `_.isArray` + source = source.replace(matchFunction(source, 'isArray'), function(match) { + return match.replace(/nativeIsArray * \|\|/, ''); }); // replace `_.keys` with `shimKeys` @@ -1475,9 +1594,8 @@ source = removeIsArgumentsFallback(source); } - - source = removeVar(source, 'reNative'); source = removeFromCreateIterator(source, 'nativeKeys'); + source = removeCreateFunction(source); } /*----------------------------------------------------------------------*/ @@ -1486,13 +1604,12 @@ // inline all functions defined with `createIterator` _.functions(lodash).forEach(function(methodName) { var reFunc = RegExp('(\\bvar ' + methodName + ' *= *)createIterator\\(((?:{|[a-zA-Z])[\\s\\S]+?)\\);\\n'); - - // skip if not defined with `createIterator` - if (!reFunc.test(source)) { - return; + if (reFunc.test(source)) { + // extract, format, and inject the compiled function's source code + source = source.replace(reFunc, function(match, captured) { + return captured + getFunctionSource(lodash[methodName]) + ';\n'; + }); } - // extract, format, and inject the compiled function's source code - source = source.replace(reFunc, '$1' + getFunctionSource(lodash[methodName]) + ';\n'); }); if (isUnderscore) { @@ -1518,15 +1635,14 @@ // replace `isArguments` and its fallback (function() { - var snippet = matchFunction(source, 'isArguments') - .replace(/function isArguments/, 'lodash.isArguments = function'); + var snippet = matchFunction(source, 'isArguments'); + snippet = snippet.replace(/function isArguments/, 'lodash.isArguments = function'); source = removeFunction(source, 'isArguments'); - source = source.replace(getIsArgumentsFallback(source), function(match) { return snippet + '\n' + match - .replace(/\bisArguments\b/g, 'lodash.$&') - .replace(/\bnoArgsClass\b/g, '!lodash.isArguments(arguments)'); + .replace(/isArguments/g, 'lodash.$&') + .replace(/noArgsClass/g, '!lodash.isArguments(arguments)'); }); }()); @@ -1542,9 +1658,11 @@ }); }); - // modify `_.every`, `_.find`, and `_.some` to use the private `indicatorObject` - source = source.replace(matchFunction(source, 'every'), function(match) { - return match.replace(/\(result *= *(.+?)\);/, '!(result = $1) && indicatorObject;'); + // modify `_.every`, `_.find`, `_.isEqual`, and `_.some` to use the private `indicatorObject` + _.each(['every', 'isEqual'], function(methodName) { + source = source.replace(matchFunction(source, methodName), function(match) { + return match.replace(/\(result *= *(.+?)\);/g, '!(result = $1) && indicatorObject;'); + }); }); source = source.replace(matchFunction(source, 'find'), function(match) { @@ -1557,7 +1675,6 @@ } else { source = removeIsArgumentsFallback(source); - source = removeVar(source, 'hasObjectSpliceBug'); // remove `hasObjectSpliceBug` fix from the mutator Array functions mixin source = source.replace(/(?:\s*\/\/.*)*\n( *)if *\(hasObjectSpliceBug[\s\S]+?\n\1}/, ''); @@ -1570,38 +1687,41 @@ ], function(data) { if (!data.flag) { source = source.replace(matchFunction(source, data.methodName), function(match) { - return match.replace(/(callback), *thisArg/g, '$1'); + return match + .replace(/(callback), *thisArg/g, '$1') + .replace(/^( *)callback *=.+/m, '$1callback || (callback = identity);') }); } }); // remove `hasDontEnumBug`, `iteratesOwnLast`, and `noArgsEnum` declarations and assignments source = source - .replace(/ *\(function\(\) *{[\s\S]+?}\(1\)\);\n/, '') + .replace(/^ *\(function\(\) *{[\s\S]+?}\(1\)\);\n/m, '') .replace(/(?:\n +\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/)?\n *var (?:hasDontEnumBug|iteratesOwnLast|noArgsEnum).+\n/g, ''); - // remove `iteratesOwnLast` from `isPlainObject` - source = source.replace(/(?:\s*\/\/.*)*\n( *)if *\(iteratesOwnLast[\s\S]+?\n\1}/, ''); - - // remove JScript [[DontEnum]] fix from `_.isEqual` - source = source.replace(/(?:\s*\/\/.*)*\n( *)if *\(hasDontEnumBug[\s\S]+?\n\1}/, ''); - - // remove `noArraySliceOnStrings` from `_.toArray` - source = source.replace(/noArraySliceOnStrings *\?[^:]+: *([^)]+)/g, '$1'); + // remove `iteratesOwnLast` from `shimIsPlainObject` + source = source.replace(matchFunction(source, 'shimIsPlainObject'), function(match) { + return match.replace(/(?:\s*\/\/.*)*\n( *)if *\(iteratesOwnLast[\s\S]+?\n\1}/, ''); + }); // remove `noCharByIndex` from `_.reduceRight` - source = source.replace(/}\s*else if *\(noCharByIndex[^}]+/, ''); + source = source.replace(matchFunction(source, 'reduceRight'), function(match) { + return match.replace(/}\s*else if *\(noCharByIndex[^}]+/, ''); + }); + + // remove `noCharByIndex` from `_.toArray` + source = source.replace(matchFunction(source, 'toArray'), function(match) { + return match.replace(/noCharByIndex[^:]+:/, ''); + }); - source = removeVar(source, 'extendIteratorOptions'); source = removeVar(source, 'iteratorTemplate'); - source = removeVar(source, 'noArraySliceOnStrings'); - source = removeVar(source, 'noCharByIndex'); + source = removeCreateFunction(source); source = removeNoArgsClass(source); source = removeNoNodeClass(source); } else { // inline `iteratorTemplate` template - source = source.replace(/(( *)var iteratorTemplate *= *)[\s\S]+?\n\2.+?;\n/, (function() { + source = source.replace(getIteratorTemplate(source), function() { var snippet = getFunctionSource(lodash._iteratorTemplate); // prepend data object references to property names to avoid having to @@ -1631,8 +1751,8 @@ // remove comments, including sourceURLs snippet = snippet.replace(/\s*\/\/.*(?:\n|$)/g, ''); - return '$1' + snippet + ';\n'; - }())); + return ' var iteratorTemplate = ' + snippet + ';\n'; + }); } } @@ -1701,6 +1821,13 @@ source = removeIsFunctionFallback(source); } if (isRemoved(source, 'mixin')) { + // simplify the `lodash` function + source = replaceFunction(source, 'lodash', [ + ' function lodash() {', + ' // no operation performed', + ' }' + ].join('\n')); + // remove `lodash.prototype` additions source = source.replace(/(?:\s*\/\/.*)*\s*mixin\(lodash\)[\s\S]+?\/\*-+\*\//, ''); source = removeVar(source, 'hasObjectSpliceBug'); @@ -1716,6 +1843,7 @@ // remove associated functions, variables, and code snippets that the minifier may miss if (isRemoved(source, 'clone')) { source = removeVar(source, 'cloneableClasses'); + source = removeVar(source, 'ctorByClass'); } if (isRemoved(source, 'isArray')) { source = removeVar(source, 'nativeIsArray'); @@ -1730,24 +1858,21 @@ // remove `templateSettings` assignment source = source.replace(/(?:\n +\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/)?\n *lodash\.templateSettings[\s\S]+?};\n/, ''); } - if (isRemoved(source, 'toArray')) { - source = removeVar(source, 'noArraySliceOnStrings'); - } - if (isRemoved(source, 'clone', 'isArguments', 'isEmpty', 'isEqual')) { + if (isRemoved(source, 'isArguments', 'isEmpty')) { source = removeNoArgsClass(source); } - if (isRemoved(source, 'isEqual', 'isPlainObject')) { + if (isRemoved(source, 'clone', 'isEqual', 'isPlainObject')) { source = removeNoNodeClass(source); } if ((source.match(/\bcreateIterator\b/g) || []).length < 2) { source = removeFunction(source, 'createIterator'); source = source.replace(/(?:\n +\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/)?\n *var noArgsEnum;|.+?noArgsEnum *=.+/g, ''); } - if (isRemoved(source, 'createIterator', 'bind')) { + if (isRemoved(source, 'createIterator', 'bind', 'keys', 'template')) { source = removeVar(source, 'isBindFast'); source = removeVar(source, 'nativeBind'); } - if (isRemoved(source, 'createIterator', 'bind', 'isArray', 'isPlainObject', 'keys')) { + if (isRemoved(source, 'createIterator', 'bind', 'isArray', 'isPlainObject', 'keys', 'template')) { source = removeVar(source, 'reNative'); } if (isRemoved(source, 'createIterator', 'isEqual')) { @@ -1804,7 +1929,7 @@ 'onComplete': function(source) { // inject "use strict" directive if (isStrict) { - source = source.replace(/^([\s\S]*?function[^{]+{)([^'"])/, '$1"use strict";$2'); + source = source.replace(/^([\s\S]*?function[^{]+{)([^"'])/, '$1"use strict";$2'); } if (isCustom) { source = addCommandsToHeader(source, options); diff --git a/build/post-install.js b/build/post-install.js index 28f008b010..9656f5af47 100644 --- a/build/post-install.js +++ b/build/post-install.js @@ -99,22 +99,28 @@ /*--------------------------------------------------------------------------*/ exec('npm -g root', function(exception, stdout) { + if (!exception) { + try { + var isGlobal = path.resolve(basePath, '..') == fs.realpathSync(stdout.trim()); + } catch(e) { + exception = e; + } + } if (exception) { console.error([ - 'There was a problem loading the npm registry. If you’re installing the Lo-Dash', - 'command-line executable (via `npm install -g lodash`), you’ll need to manually', - 'install UglifyJS and the Closure Compiler by running:', + 'Oops! There was a problem detecting the install mode. If you’re installing the', + 'Lo-Dash command-line executable (via `npm install -g lodash`), you’ll need to', + 'manually install UglifyJS and the Closure Compiler by running:', '', "curl -H 'Accept: " + mediaType + "' " + location.href + '/' + closureId + " | tar xvz -C '" + vendorPath + "'", "curl -H 'Accept: " + mediaType + "' " + location.href + '/' + uglifyId + " | tar xvz -C '" + vendorPath + "'", '', - 'Please submit an issue on the GitHub issue tracker: ' + process.env.npm_package_bugs_url + '.' + 'Please submit an issue on the GitHub issue tracker: ' + process.env.npm_package_bugs_url ].join('\n')); + console.error(exception); - process.exit(); } - // exit early if not a global install - if (path.resolve(basePath, '..') != fs.realpathSync(stdout.trim())) { + if (!isGlobal) { return; } // download the Closure Compiler diff --git a/build/pre-compile.js b/build/pre-compile.js index 2d56e4c6d2..c877082cb7 100644 --- a/build/pre-compile.js +++ b/build/pre-compile.js @@ -29,8 +29,7 @@ 'result', 'skipProto', 'source', - 'thisArg', - 'value' + 'thisArg' ]; /** Used to minify `compileIterator` option properties */ @@ -59,7 +58,6 @@ /** Used to protect the specified properties from getting minified */ var propWhitelist = [ '_', - '__chain__', '__wrapped__', 'after', 'all', @@ -190,6 +188,9 @@ 'wrap', 'zip', + // property used by the `lodash underscore` build + '__chain__', + // properties used by underscore.js '_chain', '_wrapped' @@ -214,13 +215,14 @@ if (options.isTemplate) { return source; } - // remove copyright/license header to add later in post-compile.js source = source.replace(/\/\*![\s\S]+?\*\//, ''); // add brackets to whitelisted properties so the Closure Compiler won't mung them // http://code.google.com/closure/compiler/docs/api-tutorial3.html#export - source = source.replace(RegExp('\\.(' + propWhitelist.join('|') + ')\\b', 'g'), "['$1']"); + source = source.replace(RegExp('\\.(' + propWhitelist.join('|') + ')\\b', 'g'), function(match, prop) { + return "['" + prop.replace(/['\n\r\t]/g, '\\$&') + "']"; + }); // remove brackets from `_.escape()` in `_.template` source = source.replace(/__e *= *_\['escape']/g, '__e=_.escape'); @@ -235,16 +237,25 @@ source = source.replace("result[length]['value']", 'result[length].value'); // remove whitespace from string literals - source = source.replace(/'(?:(?=(\\?))\1.)*?'/g, function(string) { + source = source.replace(/^([ "'\w]+:)? *"(?:(?=(\\?))\2.)*?"|'(?:(?=(\\?))\3.)*?'/gm, function(string, captured) { + // remove object literal property name + if (/:$/.test(captured)) { + string = string.slice(captured.length); + } // avoids removing the '\n' of the `stringEscapes` object - return string.replace(/\[object |delete |else |function | in |return\s+[\w']|throw |typeof |use strict|var |@ |'\\n'|\\\\n|\\n|\s+/g, function(match) { + string = string.replace(/\[object |delete |else |function | in |return\s+[\w"']|throw |typeof |use strict|var |@ |(["'])\\n\1|\\\\n|\\n|\s+/g, function(match) { return match == false || match == '\\n' ? '' : match; }); + // prepend object literal property name + return (captured || '') + string; }); // add newline to `+"__p+='"` in underscore.js `_.template` source = source.replace(/\+"__p\+='"/g, '+"\\n__p+=\'"'); + // add newline to `body + '}'` in `createFunction` + source = source.replace(/body *\+ *'}'/, 'body+"\\n}"'); + // remove whitespace from `_.template` related regexes source = source.replace(/(?:reEmptyString\w+|reInsertVariable) *=.+/g, function(match) { return match.replace(/ |\\n/g, ''); @@ -252,11 +263,8 @@ // remove newline from double-quoted strings in `_.template` source = source - .replace('"\';\\n__with ("', '"\';__with("') - .replace('"\\n}__\\n__p += \'"', '"}____p+=\'"') - .replace('"__p = \'"', '"__p=\'"') - .replace('"\';\\n"', '"\';"') - .replace("') {\\n'", "'){'") + .replace('"__p += \'"', '"__p+=\'"') + .replace('"\';\n"', '"\';"') // remove `useSourceURL` variable source = source.replace(/(?:\n +\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/)?\n *try *\{(?:\s*\/\/.*)*\n *var useSourceURL[\s\S]+?catch[^}]+}\n/, ''); @@ -316,8 +324,10 @@ isIteratorTemplate = /var iteratorTemplate\b/.test(snippet), modified = snippet; - // add brackets to whitelisted properties so the Closure Compiler won't mung them - modified = modified.replace(RegExp('\\.(' + iteratorOptions.join('|') + ')\\b', 'g'), "['$1']"); + // add brackets to iterator option properties so the Closure Compiler won't mung them + modified = modified.replace(RegExp('\\.(' + iteratorOptions.join('|') + ')\\b', 'g'), function(match, prop) { + return "['" + prop.replace(/['\n\r\t]/g, '\\$&') + "']"; + }); if (isCreateIterator) { // replace with modified snippet early and clip snippet to the `factory` @@ -331,9 +341,9 @@ // ensure properties in compiled strings aren't minified modified = modified.replace(RegExp('([^.]\\b)' + variable + '\\b(?!\' *[\\]:])', 'g'), '$1' + minNames[index]); - // correct `typeof x == 'object'` - if (variable == 'object') { - modified = modified.replace(RegExp("(typeof [^']+')" + minNames[index] + "'", 'g'), "$1object'"); + // correct `typeof` values + if (/^(?:boolean|function|object|number|string|undefined)$/.test(variable)) { + modified = modified.replace(RegExp("(typeof [^']+')" + minNames[index] + "'", 'g'), '$1' + variable + "'"); } }); diff --git a/doc/README.md b/doc/README.md index 5b299a0ed8..8cd0114ada 100644 --- a/doc/README.md +++ b/doc/README.md @@ -1,4 +1,4 @@ -# Lo-Dash v0.10.0 +# Lo-Dash v1.0.0-rc.1 @@ -39,7 +39,9 @@ * [`_.chain`](#_chainvalue) * [`_.tap`](#_tapvalue-interceptor) * [`_.prototype.chain`](#_prototypechain) -* [`_.prototype.value`](#_prototypevalue) +* [`_.prototype.toString`](#_prototypetostring) +* [`_.prototype.value`](#_prototypevalueof) +* [`_.prototype.valueOf`](#_prototypevalueof) @@ -52,24 +54,24 @@ * [`_.collect`](#_mapcollection--callbackidentity-thisarg) * [`_.contains`](#_containscollection-target--fromindex0) * [`_.countBy`](#_countbycollection-callbackproperty--thisarg) -* [`_.detect`](#_findcollection-callback--thisarg) -* [`_.each`](#_foreachcollection-callback--thisarg) +* [`_.detect`](#_findcollection--callbackidentity-thisarg) +* [`_.each`](#_foreachcollection--callbackidentity-thisarg) * [`_.every`](#_everycollection--callbackidentity-thisarg) * [`_.filter`](#_filtercollection--callbackidentity-thisarg) -* [`_.find`](#_findcollection-callback--thisarg) -* [`_.foldl`](#_reducecollection-callback--accumulator-thisarg) -* [`_.foldr`](#_reducerightcollection-callback--accumulator-thisarg) -* [`_.forEach`](#_foreachcollection-callback--thisarg) +* [`_.find`](#_findcollection--callbackidentity-thisarg) +* [`_.foldl`](#_reducecollection--callbackidentity-accumulator-thisarg) +* [`_.foldr`](#_reducerightcollection--callbackidentity-accumulator-thisarg) +* [`_.forEach`](#_foreachcollection--callbackidentity-thisarg) * [`_.groupBy`](#_groupbycollection-callbackproperty--thisarg) * [`_.include`](#_containscollection-target--fromindex0) -* [`_.inject`](#_reducecollection-callback--accumulator-thisarg) +* [`_.inject`](#_reducecollection--callbackidentity-accumulator-thisarg) * [`_.invoke`](#_invokecollection-methodname--arg1-arg2-) * [`_.map`](#_mapcollection--callbackidentity-thisarg) * [`_.max`](#_maxcollection--callback-thisarg) * [`_.min`](#_mincollection--callback-thisarg) * [`_.pluck`](#_pluckcollection-property) -* [`_.reduce`](#_reducecollection-callback--accumulator-thisarg) -* [`_.reduceRight`](#_reducerightcollection-callback--accumulator-thisarg) +* [`_.reduce`](#_reducecollection--callbackidentity-accumulator-thisarg) +* [`_.reduceRight`](#_reducerightcollection--callbackidentity-accumulator-thisarg) * [`_.reject`](#_rejectcollection--callbackidentity-thisarg) * [`_.select`](#_filtercollection--callbackidentity-thisarg) * [`_.shuffle`](#_shufflecollection) @@ -109,8 +111,8 @@ * [`_.clone`](#_clonevalue-deep) * [`_.defaults`](#_defaultsobject--default1-default2-) * [`_.extend`](#_assignobject--source1-source2-) -* [`_.forIn`](#_forinobject-callback--thisarg) -* [`_.forOwn`](#_forownobject-callback--thisarg) +* [`_.forIn`](#_forinobject--callbackidentity-thisarg) +* [`_.forOwn`](#_forownobject--callbackidentity-thisarg) * [`_.functions`](#_functionsobject) * [`_.has`](#_hasobject-property) * [`_.invert`](#_invertobject) @@ -185,7 +187,7 @@ ### `_.compact(array)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2576 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2634 "View in source") [Ⓣ][1] Creates an array with all falsey values of `array` removed. The values `false`, `null`, `0`, `""`, `undefined` and `NaN` are all falsey. @@ -209,7 +211,7 @@ _.compact([0, 1, false, 2, '', 3]); ### `_.difference(array [, array1, array2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2606 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2664 "View in source") [Ⓣ][1] Creates an array of `array` elements not present in the other arrays using strict equality for comparisons, i.e. `===`. @@ -234,7 +236,7 @@ _.difference([1, 2, 3, 4, 5], [5, 2, 10]); ### `_.first(array [, n])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2641 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2699 "View in source") [Ⓣ][1] Gets the first element of the `array`. Pass `n` to return the first `n` elements of the `array`. @@ -246,7 +248,7 @@ Gets the first element of the `array`. Pass `n` to return the first `n` elements 2. `[n]` *(Number)*: The number of elements to return. #### Returns -*(Mixed)*: Returns the first element or an array of the first `n` elements of `array`. +*(Mixed)*: Returns the first element, or an array of the first `n` elements, of `array`. #### Example ```js @@ -262,7 +264,7 @@ _.first([5, 4, 3, 2, 1]); ### `_.flatten(array, shallow)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2665 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2726 "View in source") [Ⓣ][1] Flattens a nested array *(the nesting can be to any depth)*. If `shallow` is truthy, `array` will only be flattened a single level. @@ -290,7 +292,7 @@ _.flatten([1, [2], [3, [[4]]]], true); ### `_.indexOf(array, value [, fromIndex=0])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2707 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2768 "View in source") [Ⓣ][1] Gets the index at which the first occurrence of `value` is found using strict equality for comparisons, i.e. `===`. If the `array` is already sorted, passing `true` for `fromIndex` will run a faster binary search. @@ -322,7 +324,7 @@ _.indexOf([1, 1, 2, 2, 3, 3], 2, true); ### `_.initial(array [, n=1])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2742 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2803 "View in source") [Ⓣ][1] Gets all but the last element of `array`. Pass `n` to exclude the last `n` elements from the result. @@ -331,7 +333,7 @@ Gets all but the last element of `array`. Pass `n` to exclude the last `n` eleme 2. `[n=1]` *(Number)*: The number of elements to exclude. #### Returns -*(Array)*: Returns all but the last element or `n` elements of `array`. +*(Array)*: Returns all but the last element, or `n` elements, of `array`. #### Example ```js @@ -347,7 +349,7 @@ _.initial([3, 2, 1]); ### `_.intersection([array1, array2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2763 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2827 "View in source") [Ⓣ][1] Computes the intersection of all the passed-in arrays using strict equality for comparisons, i.e. `===`. @@ -371,7 +373,7 @@ _.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]); ### `_.last(array [, n])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2801 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2865 "View in source") [Ⓣ][1] Gets the last element of the `array`. Pass `n` to return the last `n` elements of the `array`. @@ -380,7 +382,7 @@ Gets the last element of the `array`. Pass `n` to return the last `n` elements o 2. `[n]` *(Number)*: The number of elements to return. #### Returns -*(Mixed)*: Returns the last element or an array of the last `n` elements of `array`. +*(Mixed)*: Returns the last element, or an array of the last `n` elements, of `array`. #### Example ```js @@ -396,7 +398,7 @@ _.last([3, 2, 1]); ### `_.lastIndexOf(array, value [, fromIndex=array.length-1])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2828 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2892 "View in source") [Ⓣ][1] Gets the index at which the last occurrence of `value` is found using strict equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used as the offset from the end of the collection. @@ -425,7 +427,7 @@ _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3); ### `_.object(keys [, values=[]])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2858 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2922 "View in source") [Ⓣ][1] Creates an object composed from arrays of `keys` and `values`. Pass either a single two dimensional array, i.e. `[[key1, value1], [key2, value2]]`, or two arrays, one of `keys` and one of corresponding `values`. @@ -450,7 +452,7 @@ _.object(['moe', 'larry', 'curly'], [30, 40, 50]); ### `_.range([start=0], end [, step=1])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2903 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2967 "View in source") [Ⓣ][1] Creates an array of numbers *(positive and/or negative)* progressing from `start` up to but not including `stop`. This method is a port of Python's `range()` function. See http://docs.python.org/library/functions.html#range. @@ -488,7 +490,7 @@ _.range(0); ### `_.rest(array [, n=1])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2942 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3006 "View in source") [Ⓣ][1] The opposite of `_.initial`, this method gets all but the first value of `array`. Pass `n` to exclude the first `n` values from the result. @@ -500,7 +502,7 @@ The opposite of `_.initial`, this method gets all but the first value of `array` 2. `[n=1]` *(Number)*: The number of elements to exclude. #### Returns -*(Array)*: Returns all but the first value or `n` values of `array`. +*(Array)*: Returns all but the first element, or `n` elements, of `array`. #### Example ```js @@ -516,7 +518,7 @@ _.rest([3, 2, 1]); ### `_.sortedIndex(array, value [, callback=identity|property, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2988 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3050 "View in source") [Ⓣ][1] Uses a binary search to determine the smallest index at which the `value` should be inserted into `array` in order to maintain the sort order of the sorted `array`. If `callback` is passed, it will be executed for `value` and each element in `array` to compute their sort ranking. The `callback` is bound to `thisArg` and invoked with one argument; *(value)*. The `callback` argument may also be the name of a property to order by. @@ -560,7 +562,7 @@ _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { ### `_.union([array1, array2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3019 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3081 "View in source") [Ⓣ][1] Computes the union of the passed-in arrays using strict equality for comparisons, i.e. `===`. @@ -584,7 +586,7 @@ _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]); ### `_.uniq(array [, isSorted=false, callback=identity, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3053 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3115 "View in source") [Ⓣ][1] Creates a duplicate-value-free version of the `array` using strict equality for comparisons, i.e. `===`. If the `array` is already sorted, passing `true` for `isSorted` will run a faster algorithm. If `callback` is passed, each element of `array` is passed through a callback` before uniqueness is computed. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, index, array)*. @@ -623,7 +625,7 @@ _.uniq([1, 2, 1.5, 3, 2.5], function(num) { return this.floor(num); }, Math); ### `_.without(array [, value1, value2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3111 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3173 "View in source") [Ⓣ][1] Creates an array with all occurrences of the passed values removed using strict equality for comparisons, i.e. `===`. @@ -648,7 +650,7 @@ _.without([1, 2, 1, 0, 3, 1, 4], 0, 1); ### `_.zip([array1, array2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3142 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3204 "View in source") [Ⓣ][1] Groups the elements of each array at their corresponding indexes. Useful for separate data sources that are coordinated through matching array indexes. For a matrix of nested arrays, `_.zip.apply(...)` can transpose the matrix in a similar fashion. @@ -679,7 +681,7 @@ _.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]); ### `_(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L242 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L254 "View in source") [Ⓣ][1] The `lodash` function. @@ -697,7 +699,7 @@ The `lodash` function. ### `_.chain(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4008 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4074 "View in source") [Ⓣ][1] Wraps the value in a `lodash` wrapper object. @@ -718,8 +720,7 @@ var stooges = [ var youngest = _.chain(stooges) .sortBy(function(stooge) { return stooge.age; }) .map(function(stooge) { return stooge.name + ' is ' + stooge.age; }) - .first() - .value(); + .first(); // => 'moe is 40' ``` @@ -731,7 +732,7 @@ var youngest = _.chain(stooges) ### `_.tap(value, interceptor)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4035 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4099 "View in source") [Ⓣ][1] Invokes `interceptor` with the `value` as the first argument, and then returns `value`. The purpose of this method is to "tap into" a method chain, in order to perform operations on intermediate results within the chain. @@ -747,7 +748,7 @@ Invokes `interceptor` with the `value` as the first argument, and then returns ` _.chain([1, 2, 3, 200]) .filter(function(num) { return num % 2 == 0; }) .tap(alert) - .map(function(num) { return num * num }) + .map(function(num) { return num * num; }) .value(); // => // [2, 200] (alerted) // => [4, 40000] @@ -761,17 +762,39 @@ _.chain([1, 2, 3, 200]) ### `_.prototype.chain()` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4053 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4122 "View in source") [Ⓣ][1] -Enables method chaining on the wrapper object. +This function returns the wrapper object. Note: This function is defined to ensure the existing wrapper object is returned, instead of creating a new wrapper object like the `_.chain` method does. #### Returns *(Mixed)*: Returns the wrapper object. #### Example ```js -_([1, 2, 3]).value(); -// => [1, 2, 3] +var wrapped = _([1, 2, 3]); +wrapped === wrapped.chain(); +// => true +``` + +* * * + + + + + + +### `_.prototype.toString()` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4138 "View in source") [Ⓣ][1] + +Produces the `toString` result of the wrapped value. + +#### Returns +*(String)*: Returns the string result. + +#### Example +```js +_([1, 2, 3]).toString(); +// => '1,2,3' ``` * * * @@ -781,17 +804,20 @@ _([1, 2, 3]).value(); -### `_.prototype.value()` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4070 "View in source") [Ⓣ][1] +### `_.prototype.valueOf()` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4155 "View in source") [Ⓣ][1] Extracts the wrapped value. +#### Aliases +*value* + #### Returns *(Mixed)*: Returns the wrapped value. #### Example ```js -_([1, 2, 3]).value(); +_([1, 2, 3]).valueOf(); // => [1, 2, 3] ``` @@ -810,7 +836,7 @@ _([1, 2, 3]).value(); ### `_.contains(collection, target [, fromIndex=0])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1844 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1904 "View in source") [Ⓣ][1] Checks if a given `target` element is present in a `collection` using strict equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used as the offset from the end of the collection. @@ -848,7 +874,7 @@ _.contains('curly', 'ur'); ### `_.countBy(collection, callback|property [, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1891 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1951 "View in source") [Ⓣ][1] Creates an object composed of keys returned from running each element of `collection` through a `callback`. The corresponding value of each key is the number of times the key was returned by `callback`. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, index|key, collection)*. The `callback` argument may also be the name of a property to count by *(e.g. 'length')*. @@ -880,7 +906,7 @@ _.countBy(['one', 'two', 'three'], 'length'); ### `_.every(collection [, callback=identity, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1920 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1980 "View in source") [Ⓣ][1] Checks if the `callback` returns a truthy value for **all** elements of a `collection`. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, index|key, collection)*. @@ -909,7 +935,7 @@ _.every([true, 1, null, 'yes'], Boolean); ### `_.filter(collection [, callback=identity, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1959 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2019 "View in source") [Ⓣ][1] Examines each element in a `collection`, returning an array of all elements the `callback` returns truthy for. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, index|key, collection)*. @@ -937,8 +963,8 @@ var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }) -### `_.find(collection, callback [, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2003 "View in source") [Ⓣ][1] +### `_.find(collection [, callback=identity, thisArg])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2063 "View in source") [Ⓣ][1] Examines each element in a `collection`, returning the first one the `callback` returns truthy for. The function returns as soon as it finds an acceptable element, and does not iterate over the entire `collection`. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, index|key, collection)*. @@ -947,7 +973,7 @@ Examines each element in a `collection`, returning the first one the `callback` #### Arguments 1. `collection` *(Array|Object|String)*: The collection to iterate over. -2. `callback` *(Function)*: The function called per iteration. +2. `[callback=identity]` *(Function)*: The function called per iteration. 3. `[thisArg]` *(Mixed)*: The `this` binding of `callback`. #### Returns @@ -966,8 +992,8 @@ var even = _.find([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); -### `_.forEach(collection, callback [, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2037 "View in source") [Ⓣ][1] +### `_.forEach(collection [, callback=identity, thisArg])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2097 "View in source") [Ⓣ][1] Iterates over a `collection`, executing the `callback` for each element in the `collection`. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, index|key, collection)*. Callbacks may exit iteration early by explicitly returning `false`. @@ -976,7 +1002,7 @@ Iterates over a `collection`, executing the `callback` for each element in the ` #### Arguments 1. `collection` *(Array|Object|String)*: The collection to iterate over. -2. `callback` *(Function)*: The function called per iteration. +2. `[callback=identity]` *(Function)*: The function called per iteration. 3. `[thisArg]` *(Mixed)*: The `this` binding of `callback`. #### Returns @@ -988,7 +1014,7 @@ _([1, 2, 3]).forEach(alert).join(','); // => alerts each number and returns '1,2,3' _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, alert); -// => alerts each number (order is not guaranteed) +// => alerts each number value (order is not guaranteed) ``` * * * @@ -999,7 +1025,7 @@ _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, alert); ### `_.groupBy(collection, callback|property [, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2065 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2125 "View in source") [Ⓣ][1] Creates an object composed of keys returned from running each element of `collection` through a `callback`. The corresponding value of each key is an array of elements passed to `callback` that returned the key. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, index|key, collection)*. The `callback` argument may also be the name of a property to group by *(e.g. 'length')*. @@ -1031,7 +1057,7 @@ _.groupBy(['one', 'two', 'three'], 'length'); ### `_.invoke(collection, methodName [, arg1, arg2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2097 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2157 "View in source") [Ⓣ][1] Invokes the method named by `methodName` on each element in the `collection`, returning an array of the results of each invoked method. Additional arguments will be passed to each invoked method. If `methodName` is a function it will be invoked for, and `this` bound to, each element in the `collection`. @@ -1060,7 +1086,7 @@ _.invoke([123, 456], String.prototype.split, ''); ### `_.map(collection [, callback=identity, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2129 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2189 "View in source") [Ⓣ][1] Creates an array of values by running each element in the `collection` through a `callback`. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, index|key, collection)*. @@ -1092,7 +1118,7 @@ _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; }); ### `_.max(collection [, callback, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2171 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2231 "View in source") [Ⓣ][1] Retrieves the maximum value of an `array`. If `callback` is passed, it will be executed for each value in the `array` to generate the criterion by which the value is ranked. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, index, collection)*. @@ -1124,7 +1150,7 @@ _.max(stooges, function(stooge) { return stooge.age; }); ### `_.min(collection [, callback, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2217 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2277 "View in source") [Ⓣ][1] Retrieves the minimum value of an `array`. If `callback` is passed, it will be executed for each value in the `array` to generate the criterion by which the value is ranked. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, index, collection)*. @@ -1150,7 +1176,7 @@ _.min([10, 5, 100, 2, 1000]); ### `_.pluck(collection, property)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2266 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2326 "View in source") [Ⓣ][1] Retrieves the value of a specified property from all elements in the `collection`. @@ -1180,8 +1206,8 @@ _.pluck(stooges, 'name'); -### `_.reduce(collection, callback [, accumulator, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2294 "View in source") [Ⓣ][1] +### `_.reduce(collection [, callback=identity, accumulator, thisArg])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2350 "View in source") [Ⓣ][1] Boils down a `collection` to a single value. The initial state of the reduction is `accumulator` and each successive step of it should be returned by the `callback`. The `callback` is bound to `thisArg` and invoked with `4` arguments; for arrays they are *(accumulator, value, index|key, collection)*. @@ -1190,7 +1216,7 @@ Boils down a `collection` to a single value. The initial state of the reduction #### Arguments 1. `collection` *(Array|Object|String)*: The collection to iterate over. -2. `callback` *(Function)*: The function called per iteration. +2. `[callback=identity]` *(Function)*: The function called per iteration. 3. `[accumulator]` *(Mixed)*: Initial value of the accumulator. 4. `[thisArg]` *(Mixed)*: The `this` binding of `callback`. @@ -1210,8 +1236,8 @@ var sum = _.reduce([1, 2, 3], function(memo, num) { return memo + num; }); -### `_.reduceRight(collection, callback [, accumulator, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2323 "View in source") [Ⓣ][1] +### `_.reduceRight(collection [, callback=identity, accumulator, thisArg])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2379 "View in source") [Ⓣ][1] The right-associative version of `_.reduce`. @@ -1220,7 +1246,7 @@ The right-associative version of `_.reduce`. #### Arguments 1. `collection` *(Array|Object|String)*: The collection to iterate over. -2. `callback` *(Function)*: The function called per iteration. +2. `[callback=identity]` *(Function)*: The function called per iteration. 3. `[accumulator]` *(Mixed)*: Initial value of the accumulator. 4. `[thisArg]` *(Mixed)*: The `this` binding of `callback`. @@ -1242,7 +1268,7 @@ var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []); ### `_.reject(collection [, callback=identity, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2360 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2417 "View in source") [Ⓣ][1] The opposite of `_.filter`, this method returns the values of a `collection` that `callback` does **not** return truthy for. @@ -1268,7 +1294,7 @@ var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); ### `_.shuffle(collection)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2381 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2438 "View in source") [Ⓣ][1] Creates an array of shuffled `array` values, using a version of the Fisher-Yates shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle. @@ -1292,7 +1318,7 @@ _.shuffle([1, 2, 3, 4, 5, 6]); ### `_.size(collection)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2413 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2470 "View in source") [Ⓣ][1] Gets the size of the `collection` by returning `collection.length` for arrays and array-like objects or the number of own enumerable properties for objects. @@ -1322,7 +1348,7 @@ _.size('curly'); ### `_.some(collection [, callback=identity, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2438 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2495 "View in source") [Ⓣ][1] Checks if the `callback` returns a truthy value for **any** element of a `collection`. The function returns as soon as it finds passing value, and does not iterate over the entire `collection`. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, index|key, collection)*. @@ -1351,7 +1377,7 @@ _.some([null, 0, 'yes', false], Boolean); ### `_.sortBy(collection, callback|property [, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2484 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2541 "View in source") [Ⓣ][1] Creates an array, stable sorted in ascending order by the results of running each element of `collection` through a `callback`. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, index|key, collection)*. The `callback` argument may also be the name of a property to sort by *(e.g. 'length')*. @@ -1383,9 +1409,9 @@ _.sortBy(['larry', 'brendan', 'moe'], 'length'); ### `_.toArray(collection)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2516 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2573 "View in source") [Ⓣ][1] -Converts the `collection`, to an array. +Converts the `collection` to an array. #### Arguments 1. `collection` *(Array|Object|String)*: The collection to convert. @@ -1407,7 +1433,7 @@ Converts the `collection`, to an array. ### `_.where(collection, properties)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2546 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2604 "View in source") [Ⓣ][1] Examines each element in a `collection`, returning an array of all elements that contain the given `properties`. @@ -1445,7 +1471,7 @@ _.where(stooges, { 'age': 40 }); ### `_.after(n, func)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3175 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3237 "View in source") [Ⓣ][1] Creates a function that is restricted to executing `func` only after it is called `n` times. The `func` is executed with the `this` binding of the created function. @@ -1473,7 +1499,7 @@ _.forEach(notes, function(note) { ### `_.bind(func [, thisArg, arg1, arg2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3208 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3270 "View in source") [Ⓣ][1] Creates a function that, when called, invokes `func` with the `this` binding of `thisArg` and prepends any additional `bind` arguments to those passed to the bound function. @@ -1504,7 +1530,7 @@ func(); ### `_.bindAll(object [, methodName1, methodName2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3238 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3300 "View in source") [Ⓣ][1] Binds methods on `object` to `object`, overwriting the existing method. If no method names are provided, all the function properties of `object` will be bound. @@ -1535,7 +1561,7 @@ jQuery('#lodash_button').on('click', buttonView.onClick); ### `_.bindKey(object, key [, arg1, arg2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3284 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3346 "View in source") [Ⓣ][1] Creates a function that, when called, invokes the method at `object[key]` and prepends any additional `bindKey` arguments to those passed to the bound function. This method differs from `_.bind` by allowing bound functions to reference methods that will be redefined or don't yet exist. See http://michaux.ca/articles/lazy-function-definition-pattern. @@ -1576,7 +1602,7 @@ func(); ### `_.compose([func1, func2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3307 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3369 "View in source") [Ⓣ][1] Creates a function that is the composition of the passed functions, where each function consumes the return value of the function that follows. In math terms, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`. Each function is executed with the `this` binding of the composed function. @@ -1603,7 +1629,7 @@ welcome('moe'); ### `_.debounce(func, wait, immediate)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3340 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3402 "View in source") [Ⓣ][1] Creates a function that will delay the execution of `func` until after `wait` milliseconds have elapsed since the last time it was invoked. Pass `true` for `immediate` to cause debounce to invoke `func` on the leading, instead of the trailing, edge of the `wait` timeout. Subsequent calls to the debounced function will return the result of the last `func` call. @@ -1629,7 +1655,7 @@ jQuery(window).on('resize', lazyLayout); ### `_.defer(func [, arg1, arg2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3404 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3466 "View in source") [Ⓣ][1] Defers executing the `func` function until the current call stack has cleared. Additional arguments will be passed to `func` when it is invoked. @@ -1654,7 +1680,7 @@ _.defer(function() { alert('deferred'); }); ### `_.delay(func, wait [, arg1, arg2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3384 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3446 "View in source") [Ⓣ][1] Executes the `func` function after `wait` milliseconds. Additional arguments will be passed to `func` when it is invoked. @@ -1681,7 +1707,7 @@ _.delay(log, 1000, 'logged later'); ### `_.memoize(func [, resolver])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3428 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3490 "View in source") [Ⓣ][1] Creates a function that memoizes the result of `func`. If `resolver` is passed, it will be used to determine the cache key for storing the result based on the arguments passed to the memoized function. By default, the first argument passed to the memoized function is used as the cache key. The `func` is executed with the `this` binding of the memoized function. @@ -1707,7 +1733,7 @@ var fibonacci = _.memoize(function(n) { ### `_.once(func)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3455 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3517 "View in source") [Ⓣ][1] Creates a function that is restricted to execute `func` once. Repeat calls to the function will return the value of the first call. The `func` is executed with the `this` binding of the created function. @@ -1733,7 +1759,7 @@ initialize(); ### `_.partial(func [, arg1, arg2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3490 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3552 "View in source") [Ⓣ][1] Creates a function that, when called, invokes `func` with any additional `partial` arguments prepended to those passed to the new function. This method is similar to `bind`, except it does **not** alter the `this` binding. @@ -1760,7 +1786,7 @@ hi('moe'); ### `_.throttle(func, wait)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3512 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3574 "View in source") [Ⓣ][1] Creates a function that, when executed, will only call the `func` function at most once per every `wait` milliseconds. If the throttled function is invoked more than once during the `wait` timeout, `func` will also be called on the trailing edge of the timeout. Subsequent calls to the throttled function will return the result of the last `func` call. @@ -1785,7 +1811,7 @@ jQuery(window).on('scroll', throttled); ### `_.wrap(value, wrapper)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3564 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3627 "View in source") [Ⓣ][1] Creates a function that passes `value` to the `wrapper` function as its first argument. Additional arguments passed to the function are appended to those passed to the `wrapper` function. The `wrapper` is executed with the `this` binding of the created function. @@ -1821,7 +1847,7 @@ hello(); ### `_.assign(object [, source1, source2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L719 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L786 "View in source") [Ⓣ][1] Assigns own enumerable properties of source object(s) to the `destination` object. Subsequent sources will overwrite propery assignments of previous sources. @@ -1849,9 +1875,9 @@ _.assign({ 'name': 'moe' }, { 'age': 40 }); ### `_.clone(value, deep)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L917 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L985 "View in source") [Ⓣ][1] -Creates a clone of `value`. If `deep` is `true`, all nested objects will also be cloned otherwise they will be assigned by reference. Functions, DOM nodes, `arguments` objects, and objects created by constructors other than `Object` are **not** cloned. +Creates a clone of `value`. If `deep` is `true`, all nested objects will also be cloned, otherwise they will be assigned by reference. Functions and DOM nodes are **not** cloned. The enumerable properties of `arguments` objects and objects created by constructors other than `Object` are cloned to plain `Object` objects. Note: Lo-Dash's deep clone functionality is loosely based on the structured clone algorithm. See http://www.w3.org/TR/html5/common-dom-interfaces.html#internal-structured-cloning-algorithm. #### Arguments 1. `value` *(Mixed)*: The value to clone. @@ -1876,7 +1902,7 @@ shallow[0] === stooges[0]; // => true var deep = _.clone(stooges, true); -shallow[0] === stooges[0]; +deep[0] === stooges[0]; // => false ``` @@ -1888,7 +1914,7 @@ shallow[0] === stooges[0]; ### `_.defaults(object [, default1, default2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1000 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1073 "View in source") [Ⓣ][1] Assigns own enumerable properties of source object(s) to the `destination` object for all `destination` properties that resolve to `null`/`undefined`. Once a property is set, additional defaults of the same property will be ignored. @@ -1913,14 +1939,14 @@ _.defaults(iceCream, { 'flavor': 'vanilla', 'sprinkles': 'rainbow' }); -### `_.forIn(object, callback [, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L775 "View in source") [Ⓣ][1] +### `_.forIn(object [, callback=identity, thisArg])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L842 "View in source") [Ⓣ][1] Iterates over `object`'s own and inherited enumerable properties, executing the `callback` for each property. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, key, object)*. Callbacks may exit iteration early by explicitly returning `false`. #### Arguments 1. `object` *(Object)*: The object to iterate over. -2. `callback` *(Function)*: The function called per iteration. +2. `[callback=identity]` *(Function)*: The function called per iteration. 3. `[thisArg]` *(Mixed)*: The `this` binding of `callback`. #### Returns @@ -1949,14 +1975,14 @@ _.forIn(new Dog('Dagny'), function(value, key) { -### `_.forOwn(object, callback [, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L799 "View in source") [Ⓣ][1] +### `_.forOwn(object [, callback=identity, thisArg])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L866 "View in source") [Ⓣ][1] Iterates over an object's own enumerable properties, executing the `callback` for each property. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, key, object)*. Callbacks may exit iteration early by explicitly returning `false`. #### Arguments 1. `object` *(Object)*: The object to iterate over. -2. `callback` *(Function)*: The function called per iteration. +2. `[callback=identity]` *(Function)*: The function called per iteration. 3. `[thisArg]` *(Mixed)*: The `this` binding of `callback`. #### Returns @@ -1978,7 +2004,7 @@ _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { ### `_.functions(object)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1019 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1092 "View in source") [Ⓣ][1] Creates a sorted array of all enumerable properties, own and inherited, of `object` that have function values. @@ -2005,7 +2031,7 @@ _.functions(_); ### `_.has(object, property)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1044 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1117 "View in source") [Ⓣ][1] Checks if the specified object `property` exists and is a direct property, instead of an inherited property. @@ -2030,7 +2056,7 @@ _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b'); ### `_.invert(object)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1061 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1134 "View in source") [Ⓣ][1] Creates an object composed of the inverted keys and values of the given `object`. @@ -2054,7 +2080,7 @@ _.invert({ 'first': 'Moe', 'second': 'Larry', 'third': 'Curly' }); ### `_.isArguments(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L737 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L804 "View in source") [Ⓣ][1] Checks if `value` is an `arguments` object. @@ -2081,7 +2107,7 @@ _.isArguments([1, 2, 3]); ### `_.isArray(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1085 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1158 "View in source") [Ⓣ][1] Checks if `value` is an array. @@ -2108,7 +2134,7 @@ _.isArray([1, 2, 3]); ### `_.isBoolean(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1102 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1175 "View in source") [Ⓣ][1] Checks if `value` is a boolean *(`true` or `false`)* value. @@ -2132,7 +2158,7 @@ _.isBoolean(null); ### `_.isDate(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1119 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1192 "View in source") [Ⓣ][1] Checks if `value` is a date. @@ -2156,7 +2182,7 @@ _.isDate(new Date); ### `_.isElement(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1136 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1209 "View in source") [Ⓣ][1] Checks if `value` is a DOM element. @@ -2180,7 +2206,7 @@ _.isElement(document.body); ### `_.isEmpty(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1161 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1234 "View in source") [Ⓣ][1] Checks if `value` is empty. Arrays, strings, or `arguments` objects with a length of `0` and objects with no own enumerable properties are considered "empty". @@ -2210,7 +2236,7 @@ _.isEmpty(''); ### `_.isEqual(a, b)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1203 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1276 "View in source") [Ⓣ][1] Performs a deep comparison between two values to determine if they are equivalent to each other. @@ -2241,7 +2267,7 @@ _.isEqual(moe, clone); ### `_.isFinite(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1365 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1428 "View in source") [Ⓣ][1] Checks if `value` is, or can be coerced to, a finite number. Note: This is not the same as native `isFinite`, which will return true for booleans and empty strings. See http://es5.github.com/#x15.1.2.5. @@ -2277,7 +2303,7 @@ _.isFinite(Infinity); ### `_.isFunction(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1382 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1445 "View in source") [Ⓣ][1] Checks if `value` is a function. @@ -2301,9 +2327,9 @@ _.isFunction(_); ### `_.isNaN(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1446 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1508 "View in source") [Ⓣ][1] -Checks if `value` is `NaN`. Note: This is not the same as native `isNaN`, which will return true for `undefined` and other values. See http://es5.github.com/#x15.1.2.4. +Checks if `value` is `NaN`. Note: This is not the same as native `isNaN`, which will return `true` for `undefined` and other values. See http://es5.github.com/#x15.1.2.4. #### Arguments 1. `value` *(Mixed)*: The value to check. @@ -2334,7 +2360,7 @@ _.isNaN(undefined); ### `_.isNull(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1469 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1530 "View in source") [Ⓣ][1] Checks if `value` is `null`. @@ -2361,7 +2387,7 @@ _.isNull(undefined); ### `_.isNumber(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1486 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1547 "View in source") [Ⓣ][1] Checks if `value` is a number. @@ -2385,7 +2411,7 @@ _.isNumber(8.4 * 5); ### `_.isObject(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1412 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1475 "View in source") [Ⓣ][1] Checks if `value` is the language type of Object. *(e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)* @@ -2415,7 +2441,7 @@ _.isObject(1); ### `_.isPlainObject(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1514 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1575 "View in source") [Ⓣ][1] Checks if a given `value` is an object created by the `Object` constructor. @@ -2450,7 +2476,7 @@ _.isPlainObject({ 'name': 'moe', 'age': 40 }); ### `_.isRegExp(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1539 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1600 "View in source") [Ⓣ][1] Checks if `value` is a regular expression. @@ -2474,7 +2500,7 @@ _.isRegExp(/moe/); ### `_.isString(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1556 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1617 "View in source") [Ⓣ][1] Checks if `value` is a string. @@ -2498,7 +2524,7 @@ _.isString('moe'); ### `_.isUndefined(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1574 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1634 "View in source") [Ⓣ][1] Checks if `value` is `undefined`. @@ -2522,7 +2548,7 @@ _.isUndefined(void 0); ### `_.keys(object)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1591 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1651 "View in source") [Ⓣ][1] Creates an array composed of the own enumerable property names of `object`. @@ -2546,7 +2572,7 @@ _.keys({ 'one': 1, 'two': 2, 'three': 3 }); ### `_.merge(object [, source1, source2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1629 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1689 "View in source") [Ⓣ][1] Merges enumerable properties of the source object(s) into the `destination` object. Subsequent sources will overwrite propery assignments of previous sources. @@ -2581,7 +2607,7 @@ _.merge(stooges, ages); ### `_.omit(object, callback|[prop1, prop2, ..., thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1703 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1763 "View in source") [Ⓣ][1] Creates a shallow clone of `object` excluding the specified properties. Property names may be specified as individual arguments or as arrays of property names. If `callback` is passed, it will be executed for each property in the `object`, omitting the properties `callback` returns truthy for. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, key, object)*. @@ -2612,7 +2638,7 @@ _.omit({ 'name': 'moe', '_hint': 'knucklehead', '_seed': '96c4eb' }, function(va ### `_.pairs(object)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1737 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1797 "View in source") [Ⓣ][1] Creates a two dimensional array of the given object's key-value pairs, i.e. `[[key1, value1], [key2, value2]]`. @@ -2636,7 +2662,7 @@ _.pairs({ 'moe': 30, 'larry': 40, 'curly': 50 }); ### `_.pick(object, callback|[prop1, prop2, ..., thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1770 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1830 "View in source") [Ⓣ][1] Creates a shallow clone of `object` composed of the specified properties. Property names may be specified as individual arguments or as arrays of property names. If `callback` is passed, it will be executed for each property in the `object`, picking the properties `callback` returns truthy for. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, key, object)*. @@ -2667,7 +2693,7 @@ _.pick({ 'name': 'moe', '_hint': 'knucklehead', '_seed': '96c4eb' }, function(va ### `_.values(object)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1807 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1867 "View in source") [Ⓣ][1] Creates an array composed of the own enumerable property values of `object`. @@ -2698,7 +2724,7 @@ _.values({ 'one': 1, 'two': 2, 'three': 3 }); ### `_.escape(string)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3588 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3651 "View in source") [Ⓣ][1] Converts the characters `&`, `<`, `>`, `"`, and `'` in `string` to their corresponding HTML entities. @@ -2711,7 +2737,7 @@ Converts the characters `&`, `<`, `>`, `"`, and `'` in `string` to their corresp #### Example ```js _.escape('Moe, Larry & Curly'); -// => "Moe, Larry & Curly" +// => 'Moe, Larry & Curly' ``` * * * @@ -2722,9 +2748,9 @@ _.escape('Moe, Larry & Curly'); ### `_.identity(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3608 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3671 "View in source") [Ⓣ][1] -This function returns the first argument passed to it. Note: It is used throughout Lo-Dash as a default callback. +This function returns the first argument passed to it. Note: This function is used throughout Lo-Dash as a default callback. #### Arguments 1. `value` *(Mixed)*: Any value. @@ -2747,7 +2773,7 @@ moe === _.identity(moe); ### `_.mixin(object)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3634 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3697 "View in source") [Ⓣ][1] Adds functions properties of `object` to the `lodash` function and chainable wrapper. @@ -2777,7 +2803,7 @@ _('curly').capitalize(); ### `_.noConflict()` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3664 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3723 "View in source") [Ⓣ][1] Reverts the '_' variable to its previous value and returns a reference to the `lodash` function. @@ -2797,7 +2823,7 @@ var lodash = _.noConflict(); ### `_.random([min=0, max=1])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3687 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3746 "View in source") [Ⓣ][1] Produces a random number between `min` and `max` *(inclusive)*. If only one argument is passed, a number between `0` and the given number will be returned. @@ -2825,7 +2851,7 @@ _.random(5); ### `_.result(object, property)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3726 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3784 "View in source") [Ⓣ][1] Resolves the value of `property` on `object`. If `property` is a function it will be invoked and its result returned, else the property value is returned. If `object` is falsey, then `null` is returned. @@ -2860,7 +2886,7 @@ _.result(object, 'stuff'); ### `_.template(text, data, options)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3811 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3869 "View in source") [Ⓣ][1] A micro-templating method that handles arbitrary delimiters, preserves whitespace, and correctly escapes quotes within interpolated code. Note: In the development build `_.template` utilizes sourceURLs for easier debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl Note: Lo-Dash may be used in Chrome extensions by either creating a `lodash csp` build and avoiding `_.template` use, or loading Lo-Dash in a sandboxed page. See http://developer.chrome.com/trunk/extensions/sandboxingEval.html @@ -2934,7 +2960,7 @@ fs.writeFileSync(path.join(cwd, 'jst.js'), '\ ### `_.times(n, callback [, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3934 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4000 "View in source") [Ⓣ][1] Executes the `callback` function `n` times, returning an array of the results of each `callback` execution. The `callback` is bound to `thisArg` and invoked with one argument; *(index)*. @@ -2966,7 +2992,7 @@ _.times(3, function(n) { this.cast(n); }, mage); ### `_.unescape(string)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3960 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4026 "View in source") [Ⓣ][1] The opposite of `_.escape`, this method converts the HTML entities `&`, `<`, `>`, `"`, and `'` in `string` to their corresponding characters. @@ -2979,7 +3005,7 @@ The opposite of `_.escape`, this method converts the HTML entities `&`, `< #### Example ```js _.unescape('Moe, Larry & Curly'); -// => "Moe, Larry & Curly" +// => 'Moe, Larry & Curly' ``` * * * @@ -2990,20 +3016,23 @@ _.unescape('Moe, Larry & Curly'); ### `_.uniqueId([prefix])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3978 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4046 "View in source") [Ⓣ][1] -Generates a unique id. If `prefix` is passed, the id will be appended to it. +Generates a unique ID. If `prefix` is passed, the ID will be appended to it. #### Arguments -1. `[prefix]` *(String)*: The value to prefix the id with. +1. `[prefix]` *(String)*: The value to prefix the ID with. #### Returns -*(Number, String)*: Returns a numeric id if no prefix is passed, else a string id may be returned. +*(String)*: Returns the unique ID. #### Example ```js _.uniqueId('contact_'); // => 'contact_104' + +_.uniqueId(); +// => '105' ``` * * * @@ -3021,7 +3050,7 @@ _.uniqueId('contact_'); ### `_.VERSION` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4083 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4168 "View in source") [Ⓣ][1] *(String)*: The semantic version number. @@ -3033,7 +3062,7 @@ _.uniqueId('contact_'); ### `_.templateSettings` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L263 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L275 "View in source") [Ⓣ][1] *(Object)*: By default, the template delimiters used by Lo-Dash are similar to those in embedded Ruby *(ERB)*. Change the following template settings to use alternative delimiters. @@ -3045,7 +3074,7 @@ _.uniqueId('contact_'); ### `_.templateSettings.escape` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L272 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L284 "View in source") [Ⓣ][1] *(RegExp)*: Used to detect `data` property values to be HTML-escaped. @@ -3057,7 +3086,7 @@ _.uniqueId('contact_'); ### `_.templateSettings.evaluate` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L281 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L293 "View in source") [Ⓣ][1] *(RegExp)*: Used to detect code to be evaluated. @@ -3069,7 +3098,7 @@ _.uniqueId('contact_'); ### `_.templateSettings.interpolate` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L290 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L302 "View in source") [Ⓣ][1] *(RegExp)*: Used to detect `data` property values to inject. @@ -3081,7 +3110,7 @@ _.uniqueId('contact_'); ### `_.templateSettings.variable` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L299 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L311 "View in source") [Ⓣ][1] *(String)*: Used to reference the data object in the template text. diff --git a/doc/parse.php b/doc/parse.php index 2980b0983f..f48473c46d 100644 --- a/doc/parse.php +++ b/doc/parse.php @@ -21,7 +21,7 @@ // generate Markdown $markdown = docdown(array( 'path' => '../' . $file, - 'title' => 'Lo-Dash v0.10.0', + 'title' => 'Lo-Dash v1.0.0-rc.1', 'toc' => 'categories', 'url' => 'https://github.com/bestiejs/lodash/blob/master/lodash.js' )); diff --git a/lodash.js b/lodash.js index 3813d2af26..fa85f7f190 100644 --- a/lodash.js +++ b/lodash.js @@ -1,5 +1,5 @@ /*! - * Lo-Dash 0.10.0 + * Lo-Dash 1.0.0-rc.1 * (c) 2012 John-David Dalton * Based on Underscore.js 1.4.2 * (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc. @@ -92,7 +92,6 @@ hasOwnProperty = objectRef.hasOwnProperty, push = arrayRef.push, propertyIsEnumerable = objectRef.propertyIsEnumerable, - slice = arrayRef.slice, toString = objectRef.toString; /* Native method shortcuts for methods with the same name as other `lodash` methods */ @@ -116,6 +115,17 @@ regexpClass = '[object RegExp]', stringClass = '[object String]'; + /** Detect various environments */ + var isFirefox = !/1/.test(Function('1')), + isIeOpera = !!window.attachEvent, + isV8 = nativeBind && !/\n|true/.test(nativeBind + isIeOpera); + + /* Detect if `Function#bind` exists and is inferred to be fast (all but V8) */ + var isBindFast = nativeBind && !isV8; + + /* Detect if `Object.keys` exists and is inferred to be fast (IE, Opera, V8) */ + var isKeysFast = nativeKeys && (isIeOpera || isV8); + /** * Detect the JScript [[DontEnum]] bug: * @@ -157,9 +167,6 @@ /** Detect if an `arguments` object's [[Class]] is unresolvable (Firefox < 4, IE < 9) */ var noArgsClass = !isArguments(arguments); - /** Detect if `Array#slice` cannot be used to convert strings to arrays (Opera < 10.52) */ - var noArraySliceOnStrings = slice.call('x')[0] != 'x'; - /** * Detect lack of support for accessing string characters by index: * @@ -174,20 +181,14 @@ * a string without a `toString` property value of `typeof` "function". */ try { - var noNodeClass = ({ 'toString': 0 } + '', toString.call(window.document || 0) == objectClass); + var noNodeClass = ({ 'toString': 0 } + '', toString.call(document) == objectClass); } catch(e) { } - /* Detect if `Function#bind` exists and is inferred to be fast (all but V8) */ - var isBindFast = nativeBind && /\n|Opera/.test(nativeBind + toString.call(window.opera)); - - /* Detect if `Object.keys` exists and is inferred to be fast (IE, Opera, V8) */ - var isKeysFast = nativeKeys && /^.+$|true/.test(nativeKeys + !!window.attachEvent); - /** * Detect if sourceURL syntax is usable without erroring: * - * The JS engine in Adobe products, like InDesign, will throw a syntax error - * when it encounters a single line comment beginning with the `@` symbol. + * The JS engine embedded in Adobe products will throw a syntax error when + * it encounters a single line comment beginning with the `@` symbol. * * The JS engine in Narwhal will generate the function `function anonymous(){//}` * and throw a syntax error. @@ -197,15 +198,26 @@ * http://msdn.microsoft.com/en-us/library/121hztk3(v=vs.94).aspx */ try { - var useSourceURL = (Function('//@')(), !window.attachEvent); + var useSourceURL = (Function('//@')(), !isIeOpera); } catch(e) { } /** Used to identify object classifications that `_.clone` supports */ var cloneableClasses = {}; - cloneableClasses[argsClass] = cloneableClasses[funcClass] = false; - cloneableClasses[arrayClass] = cloneableClasses[boolClass] = cloneableClasses[dateClass] = - cloneableClasses[numberClass] = cloneableClasses[objectClass] = cloneableClasses[regexpClass] = - cloneableClasses[stringClass] = true; + cloneableClasses[funcClass] = false; + cloneableClasses[argsClass] = cloneableClasses[arrayClass] = + cloneableClasses[boolClass] = cloneableClasses[dateClass] = + cloneableClasses[numberClass] = cloneableClasses[objectClass] = + cloneableClasses[regexpClass] = cloneableClasses[stringClass] = true; + + /** Used to lookup a built-in constructor by [[Class]] */ + var ctorByClass = {}; + ctorByClass[arrayClass] = Array; + ctorByClass[boolClass] = Boolean; + ctorByClass[dateClass] = Date; + ctorByClass[objectClass] = Object; + ctorByClass[numberClass] = Number; + ctorByClass[regexpClass] = RegExp; + ctorByClass[stringClass] = String; /** Used to determine if values are of the language type Object */ var objectTypes = { @@ -240,8 +252,8 @@ * @returns {Object} Returns a `lodash` instance. */ function lodash(value) { - // exit early if already wrapped - if (value && value.__wrapped__) { + // exit early if already wrapped, even if wrapped by a different `lodash` constructor + if (value && typeof value == 'object' && value.__wrapped__) { return value; } // allow invoking `lodash` without the `new` operator @@ -301,6 +313,25 @@ /*--------------------------------------------------------------------------*/ + /** + * Creates a function from the given `args` and `body` strings. + * + * @private + * @param {String} args The comma separated function arguments. + * @param {String} body The function body. + * @returns {Function} The new function. + */ + function createFunction(args, body) { + // the newline, in `'\n}'`, is required to avoid errors if `body` ends + // with a single line comment + return window.eval('(function(' + args + ') {' + body + '\n})'); + } + // use `eval` to avoid Firefox's unoptimized `Function` constructor + // http://bugzil.la/804933 + if (isIeOpera || isV8 || !isFirefox) { + createFunction = Function; + } + /** * The template used to create iterator functions. * @@ -310,10 +341,10 @@ */ var iteratorTemplate = template( // conditional strict mode - '<% if (obj.useStrict) { %>\'use strict\';\n<% } %>' + + "<% if (obj.useStrict) { %>'use strict';\n<% } %>" + // the `iteratee` may be reassigned by the `top` snippet - 'var index, value, iteratee = <%= firstArg %>, ' + + 'var index, iteratee = <%= firstArg %>, ' + // assign the `result` variable an initial value 'result = <%= firstArg %>;\n' + // exit early if the first argument is falsey @@ -324,18 +355,17 @@ // array-like iteration: '<% if (arrayLoop) { %>' + 'var length = iteratee.length; index = -1;\n' + - 'if (typeof length == \'number\') {' + + "if (typeof length == 'number') {" + // add support for accessing string characters by index if needed ' <% if (noCharByIndex) { %>\n' + ' if (isString(iteratee)) {\n' + - ' iteratee = iteratee.split(\'\')\n' + + " iteratee = iteratee.split('')\n" + ' }' + ' <% } %>\n' + // iterate over the array-like value ' while (++index < length) {\n' + - ' value = iteratee[index];\n' + ' <%= arrayLoop %>\n' + ' }\n' + '}\n' + @@ -347,7 +377,7 @@ ' var length = iteratee.length; index = -1;\n' + ' if (length && isArguments(iteratee)) {\n' + ' while (++index < length) {\n' + - ' value = iteratee[index += \'\'];\n' + + " index += '';\n" + ' <%= objectLoop %>\n' + ' }\n' + ' } else {' + @@ -360,8 +390,8 @@ // the the `prototype` property of functions regardless of its // [[Enumerable]] value. ' <% if (!hasDontEnumBug) { %>\n' + - ' var skipProto = typeof iteratee == \'function\' && \n' + - ' propertyIsEnumerable.call(iteratee, \'prototype\');\n' + + " var skipProto = typeof iteratee == 'function' && \n" + + " propertyIsEnumerable.call(iteratee, 'prototype');\n" + ' <% } %>' + // iterate own properties using `Object.keys` if it's fast @@ -371,8 +401,7 @@ ' length = ownProps.length;\n\n' + ' while (++ownIndex < length) {\n' + ' index = ownProps[ownIndex];\n' + - ' <% if (!hasDontEnumBug) { %>if (!(skipProto && index == \'prototype\')) {\n <% } %>' + - ' value = iteratee[index];\n' + + " <% if (!hasDontEnumBug) { %>if (!(skipProto && index == 'prototype')) {\n <% } %>" + ' <%= objectLoop %>\n' + ' <% if (!hasDontEnumBug) { %>}\n<% } %>' + ' }' + @@ -381,12 +410,11 @@ ' <% } else { %>\n' + ' for (index in iteratee) {<%' + ' if (!hasDontEnumBug || useHas) { %>\n if (<%' + - ' if (!hasDontEnumBug) { %>!(skipProto && index == \'prototype\')<% }' + + " if (!hasDontEnumBug) { %>!(skipProto && index == 'prototype')<% }" + ' if (!hasDontEnumBug && useHas) { %> && <% }' + ' if (useHas) { %>hasOwnProperty.call(iteratee, index)<% }' + ' %>) {' + ' <% } %>\n' + - ' value = iteratee[index];\n' + ' <%= objectLoop %>;' + ' <% if (!hasDontEnumBug || useHas) { %>\n }<% } %>\n' + ' }' + @@ -399,12 +427,11 @@ ' <% if (hasDontEnumBug) { %>\n\n' + ' var ctor = iteratee.constructor;\n' + ' <% for (var k = 0; k < 7; k++) { %>\n' + - ' index = \'<%= shadowed[k] %>\';\n' + + " index = '<%= shadowed[k] %>';\n" + ' if (<%' + - ' if (shadowed[k] == \'constructor\') {' + + " if (shadowed[k] == 'constructor') {" + ' %>!(ctor && ctor.prototype === iteratee) && <%' + ' } %>hasOwnProperty.call(iteratee, index)) {\n' + - ' value = iteratee[index];\n' + ' <%= objectLoop %>\n' + ' }' + ' <% } %>' + @@ -421,9 +448,9 @@ var assignIteratorOptions = { 'args': 'object, source, guard', 'top': - 'for (var argsIndex = 1, argsLength = typeof guard == \'number\' ? 2 : arguments.length; argsIndex < argsLength; argsIndex++) {\n' + + "for (var argsIndex = 1, argsLength = typeof guard == 'number' ? 2 : arguments.length; argsIndex < argsLength; argsIndex++) {\n" + ' if ((iteratee = arguments[argsIndex])) {', - 'objectLoop': 'result[index] = value', + 'objectLoop': 'result[index] = iteratee[index]', 'bottom': ' }\n}' }; @@ -432,9 +459,9 @@ */ var forEachIteratorOptions = { 'args': 'collection, callback, thisArg', - 'top': 'callback = createCallback(callback, thisArg)', - 'arrayLoop': 'if (callback(value, index, collection) === false) return result', - 'objectLoop': 'if (callback(value, index, collection) === false) return result' + 'top': "callback = callback && typeof thisArg == 'undefined' ? callback : createCallback(callback, thisArg)", + 'arrayLoop': 'if (callback(iteratee[index], index, collection) === false) return result', + 'objectLoop': 'if (callback(iteratee[index], index, collection) === false) return result' }; /** Reusable iterator options for `forIn` and `forOwn` */ @@ -512,10 +539,10 @@ // ensure a stable sort in V8 and other engines // http://code.google.com/p/v8/issues/detail?id=90 if (a !== b) { - if (a > b || a === undefined) { + if (a > b || typeof a == 'undefined') { return 1; } - if (a < b || b === undefined) { + if (a < b || typeof b == 'undefined') { return -1; } } @@ -557,20 +584,19 @@ } if (partialArgs.length) { args = args.length - ? partialArgs.concat(slice.call(args)) + ? partialArgs.concat(slice(args)) : partialArgs; } if (this instanceof bound) { - // get `func` instance if `bound` is invoked in a `new` expression + // ensure `new bound` is an instance of `bound` and `func` noop.prototype = func.prototype; thisBinding = new noop; + noop.prototype = null; // mimic the constructor's `return` behavior // http://es5.github.com/#x13.2.2 var result = func.apply(thisBinding, args); - return isObject(result) - ? result - : thisBinding + return isObject(result) ? result : thisBinding; } return func.apply(thisBinding, args); } @@ -596,7 +622,7 @@ return object[func]; }; } - if (thisArg !== undefined) { + if (typeof thisArg != 'undefined') { return function(value, index, object) { return func.call(thisArg, value, index, object); }; @@ -642,7 +668,7 @@ data.firstArg = /^[^,]+/.exec(args)[0]; // create the function factory - var factory = Function( + var factory = createFunction( 'createCallback, hasOwnProperty, isArguments, isString, objectTypes, ' + 'nativeKeys, propertyIsEnumerable', 'return function(' + args + ') {\n' + iteratorTemplate(data) + '\n}' @@ -677,6 +703,19 @@ return htmlEscapes[match]; } + /** + * Checks if `value` is a DOM node in IE < 9. + * + * @private + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true` if the `value` is a DOM node, else `false`. + */ + function isNode(value) { + // IE < 9 presents DOM nodes as `Object` objects except they have `toString` + // methods that are `typeof` "string" and still can coerce nodes to strings + return typeof value.toString != 'function' && typeof (value + '') == 'string'; + } + /** * A no-operation function. * @@ -686,6 +725,34 @@ // no operation performed } + /** + * Slices the `collection` from the `start` index up to, but not including, + * the `end` index. + * + * Note: This function is used, instead of `Array#slice`, to support node lists + * in IE < 9 and to ensure dense arrays are returned. + * + * @private + * @param {Array|Object|String} collection The collection to slice. + * @param {Number} start The start index. + * @param {Number} end The end index. + * @returns {Array} Returns the new array. + */ + function slice(array, start, end) { + start || (start = 0); + if (typeof end == 'undefined') { + end = array ? array.length : 0; + } + var index = -1, + length = end - start || 0, + result = Array(length < 0 ? 0 : length); + + while (++index < length) { + result[index] = array[start + index]; + } + return result; + } + /** * Used by `unescape` to convert HTML entities to characters. * @@ -754,7 +821,7 @@ * @memberOf _ * @category Objects * @param {Object} object The object to iterate over. - * @param {Function} callback The function called per iteration. + * @param {Function} [callback=identity] The function called per iteration. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns `object`. * @example @@ -786,7 +853,7 @@ * @memberOf _ * @category Objects * @param {Object} object The object to iterate over. - * @param {Function} callback The function called per iteration. + * @param {Function} [callback=identity] The function called per iteration. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns `object`. * @example @@ -814,12 +881,9 @@ if (!(value && typeof value == 'object') || isArguments(value)) { return result; } - // IE < 9 presents DOM nodes as `Object` objects except they have `toString` - // methods that are `typeof` "string" and still can coerce nodes to strings. - // Also check that the constructor is `Object` (i.e. `Object instanceof Object`) + // check that the constructor is `Object` (i.e. `Object instanceof Object`) var ctor = value.constructor; - if ((!noNodeClass || !(typeof value.toString != 'function' && typeof (value + '') == 'string')) && - (!isFunction(ctor) || ctor instanceof ctor)) { + if ((!isFunction(ctor) && (!noNodeClass || !isNode(value))) || ctor instanceof ctor) { // IE < 9 iterates inherited properties before own properties. If the first // iterated property is an object's own property then there are no inherited // enumerable properties. @@ -880,9 +944,13 @@ /** * Creates a clone of `value`. If `deep` is `true`, all nested objects will - * also be cloned otherwise they will be assigned by reference. Functions, DOM - * nodes, `arguments` objects, and objects created by constructors other than - * `Object` are **not** cloned. + * also be cloned, otherwise they will be assigned by reference. Functions and + * DOM nodes are **not** cloned. The enumerable properties of `arguments` objects + * and objects created by constructors other than `Object` are cloned to plain + * `Object` objects. + * + * Note: Lo-Dash's deep clone functionality is loosely based on the structured clone algorithm. + * See http://www.w3.org/TR/html5/common-dom-interfaces.html#internal-structured-cloning-algorithm. * * @static * @memberOf _ @@ -911,7 +979,7 @@ * // => true * * var deep = _.clone(stooges, true); - * shallow[0] === stooges[0]; + * deep[0] === stooges[0]; * // => false */ function clone(value, deep, guard, stackA, stackB) { @@ -924,23 +992,19 @@ // inspect [[Class]] var isObj = isObject(value); if (isObj) { - // don't clone `arguments` objects, functions, or non-object Objects var className = toString.call(value); - if (!cloneableClasses[className] || (noArgsClass && isArguments(value))) { + if (!cloneableClasses[className] || (noNodeClass && isNode(value))) { return value; } - var isArr = className == arrayClass; - isObj = isArr || (className == objectClass ? isPlainObject(value) : isObj); + var isArr = isArray(value); } // shallow clone if (!isObj || !deep) { - // don't clone functions return isObj - ? (isArr ? slice.call(value) : assign({}, value)) + ? (isArr ? slice(value) : assign({}, value)) : value; } - - var ctor = value.constructor; + var ctor = ctorByClass[className]; switch (className) { case boolClass: case dateClass: @@ -976,6 +1040,15 @@ result[key] = clone(objValue, deep, null, stackA, stackB); }); + // add array properties assigned by `RegExp#exec` + if (isArr) { + if (hasOwnProperty.call(value, 'index')) { + result.index = value.index; + } + if (hasOwnProperty.call(value, 'input')) { + result.input = value.input; + } + } return result; } @@ -1211,8 +1284,16 @@ return a === b; } // compare [[Class]] names - var className = toString.call(a); - if (className != toString.call(b)) { + var className = toString.call(a), + otherName = toString.call(b); + + if (className == argsClass) { + className = objectClass; + } + if (otherName == argsClass) { + otherName = objectClass; + } + if (className != otherName) { return false; } switch (className) { @@ -1235,24 +1316,19 @@ // treat string primitives and their corresponding object instances as equal return a == b + ''; } - // exit early, in older browsers, if `a` is array-like but not `b` - var isArr = className == arrayClass || className == argsClass; - if (noArgsClass && !isArr && (isArr = isArguments(a)) && !isArguments(b)) { - return false; - } + var isArr = className == arrayClass; if (!isArr) { // unwrap any `lodash` wrapped values if (a.__wrapped__ || b.__wrapped__) { return isEqual(a.__wrapped__ || a, b.__wrapped__ || b); } // exit for functions and DOM nodes - if (className != objectClass || (noNodeClass && ( - (typeof a.toString != 'function' && typeof (a + '') == 'string') || - (typeof b.toString != 'function' && typeof (b + '') == 'string')))) { + if (className != objectClass || (noNodeClass && (isNode(a) || isNode(b)))) { return false; } - var ctorA = a.constructor, - ctorB = b.constructor; + // in older versions of Opera, `arguments` objects have `Array` constructors + var ctorA = noArgsClass && isArguments(a) ? Object : a.constructor, + ctorB = noArgsClass && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !( @@ -1274,7 +1350,6 @@ return stackB[length] == b; } } - var index = -1, result = true, size = 0; @@ -1299,38 +1374,27 @@ } return result; } - // deep compare objects - for (var key in a) { + // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` + // which, in this case, is more costly + forIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // count the number of properties. size++; // deep compare each property value. - if (!(hasOwnProperty.call(b, key) && isEqual(a[key], b[key], stackA, stackB))) { - return false; - } + return (result = hasOwnProperty.call(b, key) && isEqual(value, b[key], stackA, stackB)); } - } - // ensure both objects have the same number of properties - for (key in b) { - // The JS engine in Adobe products, like InDesign, has a bug that causes - // `!size--` to throw an error so it must be wrapped in parentheses. - // https://github.com/documentcloud/underscore/issues/355 - if (hasOwnProperty.call(b, key) && !(size--)) { - // `size` will be `-1` if `b` has more properties than `a` - return false; - } - } - // handle JScript [[DontEnum]] bug - if (hasDontEnumBug) { - while (++index < 7) { - key = shadowed[index]; - if (hasOwnProperty.call(a, key) && - !(hasOwnProperty.call(b, key) && isEqual(a[key], b[key], stackA, stackB))) { - return false; + }); + + if (result) { + // ensure both objects have the same number of properties + forIn(b, function(value, key, b) { + if (hasOwnProperty.call(b, key)) { + // `size` will be `-1` if `b` has more properties than `a` + return (result = --size > -1); } - } + }); } - return true; + return result; } /** @@ -1339,7 +1403,6 @@ * Note: This is not the same as native `isFinite`, which will return true for * booleans and empty strings. See http://es5.github.com/#x15.1.2.5. * - * @deprecated * @static * @memberOf _ * @category Objects @@ -1420,10 +1483,9 @@ /** * Checks if `value` is `NaN`. * - * Note: This is not the same as native `isNaN`, which will return true for + * Note: This is not the same as native `isNaN`, which will return `true` for * `undefined` and other values. See http://es5.github.com/#x15.1.2.4. * - * @deprecated * @static * @memberOf _ * @category Objects @@ -1446,13 +1508,12 @@ function isNaN(value) { // `NaN` as a primitive is the only value that is not equal to itself // (perform the [[Class]] check first to avoid errors with some host objects in IE) - return toString.call(value) == numberClass && value != +value + return isNumber(value) && value != +value } /** * Checks if `value` is `null`. * - * @deprecated * @static * @memberOf _ * @category Objects @@ -1484,7 +1545,7 @@ * // => true */ function isNumber(value) { - return toString.call(value) == numberClass; + return typeof value == 'number' || toString.call(value) == numberClass; } /** @@ -1554,13 +1615,12 @@ * // => true */ function isString(value) { - return toString.call(value) == stringClass; + return typeof value == 'string' || toString.call(value) == stringClass; } /** * Checks if `value` is `undefined`. * - * @deprecated * @static * @memberOf _ * @category Objects @@ -1572,7 +1632,7 @@ * // => true */ function isUndefined(value) { - return value === undefined; + return typeof value == 'undefined'; } /** @@ -1991,7 +2051,7 @@ * @alias detect * @category Collections * @param {Array|Object|String} collection The collection to iterate over. - * @param {Function} callback The function called per iteration. + * @param {Function} [callback=identity] The function called per iteration. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Mixed} Returns the element that passed the callback check, * else `undefined`. @@ -2023,7 +2083,7 @@ * @alias each * @category Collections * @param {Array|Object|String} collection The collection to iterate over. - * @param {Function} callback The function called per iteration. + * @param {Function} [callback=identity] The function called per iteration. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Array|Object|String} Returns `collection`. * @example @@ -2032,7 +2092,7 @@ * // => alerts each number and returns '1,2,3' * * _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, alert); - * // => alerts each number (order is not guaranteed) + * // => alerts each number value (order is not guaranteed) */ var forEach = createIterator(forEachIteratorOptions); @@ -2095,7 +2155,7 @@ * // => [['1', '2', '3'], ['4', '5', '6']] */ function invoke(collection, methodName) { - var args = slice.call(arguments, 2), + var args = slice(arguments, 2), isFunc = typeof methodName == 'function', result = []; @@ -2264,11 +2324,7 @@ * // => ['moe', 'larry', 'curly'] */ function pluck(collection, property) { - var result = []; - forEach(collection, function(value) { - result.push(value[property]); - }); - return result; + return map(collection, property + ''); } /** @@ -2282,7 +2338,7 @@ * @alias foldl, inject * @category Collections * @param {Array|Object|String} collection The collection to iterate over. - * @param {Function} callback The function called per iteration. + * @param {Function} [callback=identity] The function called per iteration. * @param {Mixed} [accumulator] Initial value of the accumulator. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Mixed} Returns the accumulated value. @@ -2293,11 +2349,11 @@ */ function reduce(collection, callback, accumulator, thisArg) { var noaccum = arguments.length < 3; - callback = createCallback(callback, thisArg); + callback || (callback = identity); forEach(collection, function(value, index, collection) { accumulator = noaccum ? (noaccum = false, value) - : callback(accumulator, value, index, collection) + : callback.call(thisArg, accumulator, value, index, collection) }); return accumulator; } @@ -2310,7 +2366,7 @@ * @alias foldr * @category Collections * @param {Array|Object|String} collection The collection to iterate over. - * @param {Function} callback The function called per iteration. + * @param {Function} [callback=identity] The function called per iteration. * @param {Mixed} [accumulator] Initial value of the accumulator. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Mixed} Returns the accumulated value. @@ -2331,6 +2387,7 @@ } else if (noCharByIndex && isString(collection)) { iteratee = collection.split(''); } + callback || (callback = identity); forEach(collection, function(value, index, collection) { index = props ? props[--length] : --length; accumulator = noaccum @@ -2501,7 +2558,7 @@ } /** - * Converts the `collection`, to an array. + * Converts the `collection` to an array. * * @static * @memberOf _ @@ -2514,10 +2571,11 @@ * // => [2, 3, 4] */ function toArray(collection) { - if (collection && typeof collection.length == 'number') { - return (noArraySliceOnStrings ? isString(collection) : typeof collection == 'string') + var length = collection ? collection.length : 0; + if (typeof length == 'number') { + return noCharByIndex && isString(collection) ? collection.split('') - : slice.call(collection); + : slice(collection); } return values(collection); } @@ -2631,8 +2689,8 @@ * @param {Number} [n] The number of elements to return. * @param- {Object} [guard] Internally used to allow this method to work with * others like `_.map` without using their callback `index` argument for `n`. - * @returns {Mixed} Returns the first element or an array of the first `n` - * elements of `array`. + * @returns {Mixed} Returns the first element, or an array of the first `n` + * elements, of `array`. * @example * * _.first([5, 4, 3, 2, 1]); @@ -2640,7 +2698,10 @@ */ function first(array, n, guard) { if (array) { - return (n == null || guard) ? array[0] : slice.call(array, 0, n); + var length = array.length; + return (n == null || guard) + ? array[0] + : slice(array, 0, nativeMin(nativeMax(0, n), length)); } } @@ -2733,16 +2794,19 @@ * @param {Number} [n=1] The number of elements to exclude. * @param- {Object} [guard] Internally used to allow this method to work with * others like `_.map` without using their callback `index` argument for `n`. - * @returns {Array} Returns all but the last element or `n` elements of `array`. + * @returns {Array} Returns all but the last element, or `n` elements, of `array`. * @example * * _.initial([3, 2, 1]); * // => [3, 2] */ function initial(array, n, guard) { - return array - ? slice.call(array, 0, -((n == null || guard) ? 1 : n)) - : []; + if (!array) { + return []; + } + var length = array.length; + n = n == null || guard ? 1 : n || 0; + return slice(array, 0, nativeMin(nativeMax(0, length - n), length)); } /** @@ -2791,8 +2855,8 @@ * @param {Number} [n] The number of elements to return. * @param- {Object} [guard] Internally used to allow this method to work with * others like `_.map` without using their callback `index` argument for `n`. - * @returns {Mixed} Returns the last element or an array of the last `n` - * elements of `array`. + * @returns {Mixed} Returns the last element, or an array of the last `n` + * elements, of `array`. * @example * * _.last([3, 2, 1]); @@ -2801,7 +2865,7 @@ function last(array, n, guard) { if (array) { var length = array.length; - return (n == null || guard) ? array[length - 1] : slice.call(array, -n || length); + return (n == null || guard) ? array[length - 1] : slice(array, nativeMax(0, length - n)); } } @@ -2909,7 +2973,7 @@ start = 0; } // use `Array(length)` so V8 will avoid the slower "dictionary" mode - // http://www.youtube.com/watch?v=XAqIpGU8ZZk#t=16m27s + // http://youtu.be/XAqIpGU8ZZk#t=17m25s var index = -1, length = nativeMax(0, ceil((end - start) / step)), result = Array(length); @@ -2933,16 +2997,14 @@ * @param {Number} [n=1] The number of elements to exclude. * @param- {Object} [guard] Internally used to allow this method to work with * others like `_.map` without using their callback `index` argument for `n`. - * @returns {Array} Returns all but the first value or `n` values of `array`. + * @returns {Array} Returns all but the first element, or `n` elements, of `array`. * @example * * _.rest([3, 2, 1]); * // => [2, 1] */ function rest(array, n, guard) { - return array - ? slice.call(array, (n == null || guard) ? 1 : n) - : []; + return slice(array, (n == null || guard) ? 1 : nativeMax(0, n)); } /** @@ -3210,7 +3272,7 @@ // (in V8 `Function#bind` is slower except when partially applied) return isBindFast || (nativeBind && arguments.length > 2) ? nativeBind.call.apply(nativeBind, arguments) - : createBound(func, thisArg, slice.call(arguments, 2)); + : createBound(func, thisArg, slice(arguments, 2)); } /** @@ -3282,7 +3344,7 @@ * // => 'hi, moe!' */ function bindKey(object, key) { - return createBound(object, key, slice.call(arguments, 2)); + return createBound(object, key, slice(arguments, 2)); } /** @@ -3382,7 +3444,7 @@ * // => 'logged later' (Appears after one second.) */ function delay(func, wait) { - var args = slice.call(arguments, 2); + var args = slice(arguments, 2); return setTimeout(function() { func.apply(undefined, args); }, wait); } @@ -3402,7 +3464,7 @@ * // returns from the function before `alert` is called */ function defer(func) { - var args = slice.call(arguments, 1); + var args = slice(arguments, 1); return setTimeout(function() { func.apply(undefined, args); }, 1); } @@ -3488,7 +3550,7 @@ * // => 'hi: moe' */ function partial(func) { - return createBound(func, slice.call(arguments, 1)); + return createBound(func, slice(arguments, 1)); } /** @@ -3530,6 +3592,7 @@ if (remaining <= 0) { clearTimeout(timeoutId); + timeoutId = null; lastCalled = now; result = func.apply(thisArg, args); } @@ -3583,7 +3646,7 @@ * @example * * _.escape('Moe, Larry & Curly'); - * // => "Moe, Larry & Curly" + * // => 'Moe, Larry & Curly' */ function escape(string) { return string == null ? '' : (string + '').replace(reUnescapedHtml, escapeHtmlChar); @@ -3592,7 +3655,7 @@ /** * This function returns the first argument passed to it. * - * Note: It is used throughout Lo-Dash as a default callback. + * Note: This function is used throughout Lo-Dash as a default callback. * * @static * @memberOf _ @@ -3640,11 +3703,7 @@ push.apply(args, arguments); var result = func.apply(lodash, args); - if (this.__chain__) { - result = new lodash(result); - result.__chain__ = true; - } - return result; + return new lodash(result); }; }); } @@ -3701,7 +3760,6 @@ * it will be invoked and its result returned, else the property value is * returned. If `object` is falsey, then `null` is returned. * - * @deprecated * @static * @memberOf _ * @category Utilities @@ -3840,13 +3898,21 @@ source += text.slice(index, offset).replace(reUnescapedString, escapeStringChar); // replace delimiters with snippets - source += - escapeValue ? "' +\n__e(" + escapeValue + ") +\n'" : - evaluateValue ? "';\n" + evaluateValue + ";\n__p += '" : - interpolateValue ? "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'" : ''; - + if (escapeValue) { + source += "' +\n__e(" + escapeValue + ") +\n'"; + } + if (evaluateValue) { + source += "';\n" + evaluateValue + ";\n__p += '"; + } + if (interpolateValue) { + source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"; + } isEvaluating || (isEvaluating = evaluateValue || reComplexDelimiter.test(escapeValue || interpolateValue)); index = offset + match.length; + + // the JS engine embedded in Adobe products requires returning the `match` + // string in order to produce the correct `offset` value + return match; }); source += "';\n"; @@ -3876,10 +3942,10 @@ // frame code as the function body source = 'function(' + variable + ') {\n' + (hasVariable ? '' : variable + ' || (' + variable + ' = {});\n') + - 'var __t, __p = \'\', __e = _.escape' + + "var __t, __p = '', __e = _.escape" + (isEvaluating ? ', __j = Array.prototype.join;\n' + - 'function print() { __p += __j.call(arguments, \'\') }\n' + "function print() { __p += __j.call(arguments, '') }\n" : (hasVariable ? '' : ', __d = ' + variable + '.' + variable + ' || ' + variable) + ';\n' ) + source + @@ -3892,7 +3958,7 @@ : ''; try { - result = Function('_', 'return ' + source + sourceURL)(lodash); + result = createFunction('_', 'return ' + source + sourceURL)(lodash); } catch(e) { e.source = source; throw e; @@ -3955,29 +4021,30 @@ * @example * * _.unescape('Moe, Larry & Curly'); - * // => "Moe, Larry & Curly" + * // => 'Moe, Larry & Curly' */ function unescape(string) { return string == null ? '' : (string + '').replace(reEscapedHtml, unescapeHtmlChar); } /** - * Generates a unique id. If `prefix` is passed, the id will be appended to it. + * Generates a unique ID. If `prefix` is passed, the ID will be appended to it. * * @static * @memberOf _ * @category Utilities - * @param {String} [prefix] The value to prefix the id with. - * @returns {Number|String} Returns a numeric id if no prefix is passed, else - * a string id may be returned. + * @param {String} [prefix] The value to prefix the ID with. + * @returns {String} Returns the unique ID. * @example * * _.uniqueId('contact_'); * // => 'contact_104' + * + * _.uniqueId(); + * // => '105' */ function uniqueId(prefix) { - var id = idCounter++; - return prefix ? prefix + id : id; + return (prefix == null ? '' : prefix + '') + (++idCounter); } /*--------------------------------------------------------------------------*/ @@ -4001,14 +4068,11 @@ * var youngest = _.chain(stooges) * .sortBy(function(stooge) { return stooge.age; }) * .map(function(stooge) { return stooge.name + ' is ' + stooge.age; }) - * .first() - * .value(); + * .first(); * // => 'moe is 40' */ function chain(value) { - value = new lodash(value); - value.__chain__ = true; - return value; + return new lodash(value); } /** @@ -4027,7 +4091,7 @@ * _.chain([1, 2, 3, 200]) * .filter(function(num) { return num % 2 == 0; }) * .tap(alert) - * .map(function(num) { return num * num }) + * .map(function(num) { return num * num; }) * .value(); * // => // [2, 200] (alerted) * // => [4, 40000] @@ -4038,7 +4102,11 @@ } /** - * Enables method chaining on the wrapper object. + * This function returns the wrapper object. + * + * Note: This function is defined to ensure the existing wrapper object is + * returned, instead of creating a new wrapper object like the `_.chain` + * method does. * * @name chain * @deprecated @@ -4047,27 +4115,44 @@ * @returns {Mixed} Returns the wrapper object. * @example * - * _([1, 2, 3]).value(); - * // => [1, 2, 3] + * var wrapped = _([1, 2, 3]); + * wrapped === wrapped.chain(); + * // => true */ function wrapperChain() { - this.__chain__ = true; return this; } + /** + * Produces the `toString` result of the wrapped value. + * + * @name toString + * @memberOf _ + * @category Chaining + * @returns {String} Returns the string result. + * @example + * + * _([1, 2, 3]).toString(); + * // => '1,2,3' + */ + function wrapperToString() { + return String(this.__wrapped__); + } + /** * Extracts the wrapped value. * - * @name value + * @name valueOf * @memberOf _ + * @alias value * @category Chaining * @returns {Mixed} Returns the wrapped value. * @example * - * _([1, 2, 3]).value(); + * _([1, 2, 3]).valueOf(); * // => [1, 2, 3] */ - function wrapperValue() { + function wrapperValueOf() { return this.__wrapped__; } @@ -4080,7 +4165,7 @@ * @memberOf _ * @type String */ - lodash.VERSION = '0.10.0'; + lodash.VERSION = '1.0.0-rc.1'; // assign static methods lodash.assign = assign; @@ -4208,7 +4293,35 @@ // add `lodash.prototype.chain` after calling `mixin()` to avoid overwriting // it with the wrapped `lodash.chain` lodash.prototype.chain = wrapperChain; - lodash.prototype.value = wrapperValue; + lodash.prototype.toString = wrapperToString; + lodash.prototype.value = wrapperValueOf; + lodash.prototype.valueOf = wrapperValueOf; + + // add methods that are capable of returning wrapped and unwrapped values + forEach(['first', 'last'], function(methodName) { + var func = lodash[methodName]; + if (func) { + lodash.prototype[methodName] = function(n, guard) { + var result = func(this.__wrapped__, n, guard); + return (n == null || guard) + ? result + : new lodash(result); + }; + } + }); + + // add all methods that return unwrapped values + forEach(filter(functions(lodash), function(methodName) { + return /^(?:bind|contains|every|find|has|is[A-Z].+|reduce.*|some)$/.test(methodName); + }), function(methodName) { + var func = lodash[methodName]; + + lodash.prototype[methodName] = function() { + var args = [this.__wrapped__]; + push.apply(args, arguments); + return func.apply(lodash, args); + }; + }); // add all mutator Array functions to the wrapper. forEach(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(methodName) { @@ -4223,11 +4336,7 @@ if (hasObjectSpliceBug && value.length === 0) { delete value[0]; } - if (this.__chain__) { - value = new lodash(value); - value.__chain__ = true; - } - return value; + return this; }; }); @@ -4239,11 +4348,7 @@ var value = this.__wrapped__, result = func.apply(value, arguments); - if (this.__chain__) { - result = new lodash(result); - result.__chain__ = true; - } - return result; + return new lodash(result); }; }); diff --git a/lodash.min.js b/lodash.min.js index b51a3611e8..19c70c791f 100644 --- a/lodash.min.js +++ b/lodash.min.js @@ -1,40 +1,41 @@ /*! - Lo-Dash 0.10.0 lodash.com/license + Lo-Dash 1.0.0-rc.1 lodash.com/license Underscore.js 1.4.2 underscorejs.org/LICENSE */ -;(function(e,t){function s(e){if(e&&e.__wrapped__)return e;if(!(this instanceof s))return new s(e);this.__wrapped__=e}function o(e,t,n){t||(t=0);var r=e.length,i=r-t>=(n||Z);if(i)for(var s={},n=t-1;++nn||e===t)return 1;if(ei;i++)r+="i='"+e.j[i]+"';if(","constructor"==e.j[i]&&(r+="!(f&&f.prototype===l)&&"),r+="h.call(l,i)){x=l[i];"+e.g+"}"}if(e.b||e.h)r+="}";return r+=e.c+";return t",Function("e,h,j,k,p,n,s","return function("+t+"){"+r+"}")(l,bt,m,N,Yt,Lt,Et)}function h(e){return"\\"+ -Zt[e]}function p(e){return un[e]}function d(){}function v(e){return an[e]}function m(e){return xt.call(e)==_t}function g(e){var t=i;if(!e||"object"!=typeof e||m(e))return t;var n=e.constructor;return(!$t||"function"==typeof e.toString||"string"!=typeof (e+""))&&(!x(n)||n instanceof n)?Rt?(sn(e,function(e,n,r){return t=!bt.call(r,n),i}),t===i):(sn(e,function(e,n){t=n}),t===i||bt.call(e,t)):t}function y(e){var t=[];return on(e,function(e,n){t.push(n)}),t}function b(e,t,n,s,o){if(e==r)return e;n&&(t= -i);if(n=T(e)){var u=xt.call(e);if(!Gt[u]||Wt&&m(e))return e;var a=u==Dt,n=a||(u==jt?cn(e):n)}if(!n||!t)return n?a?St.call(e):rn({},e):e;n=e.constructor;switch(u){case Pt:case Ht:return new n(+e);case Bt:case It:return new n(e);case Ft:return n(e.source,ot.exec(e))}s||(s=[]),o||(o=[]);for(u=s.length;u--;)if(s[u]==e)return o[u];var f=a?n(e.length):{};return s.push(e),o.push(f),(a?pn:on)(e,function(e,n){f[n]=b(e,t,r,s,o)}),f}function w(e){var t=[];return sn(e,function(e,n){x(e)&&t.push(n)}),t.sort() -}function E(e){var t={};return on(e,function(e,n){t[e]=n}),t}function S(e,t,s,o){if(e===t)return 0!==e||1/e==1/t;if(e==r||t==r)return e===t;var u=xt.call(e);if(u!=xt.call(t))return i;switch(u){case Pt:case Ht:return+e==+t;case Bt:return e!=+e?t!=+t:0==e?1/e==1/t:e==+t;case Ft:case It:return e==t+""}var a=u==Dt||u==_t;if(Wt&&!a&&(a=m(e))&&!m(t))return i;if(!a){if(e.__wrapped__||t.__wrapped__)return S(e.__wrapped__||e,t.__wrapped__||t);if(u!=jt||$t&&("function"!=typeof e.toString&&"string"==typeof -(e+"")||"function"!=typeof t.toString&&"string"==typeof (t+"")))return i;var u=e.constructor,f=t.constructor;if(u!=f&&(!x(u)||!(u instanceof u&&x(f)&&f instanceof f)))return i}s||(s=[]),o||(o=[]);for(u=s.length;u--;)if(s[u]==e)return o[u]==t;var u=-1,f=n,l=0;s.push(e),o.push(t);if(a){l=e.length;if(f=l==t.length)for(;l--&&(f=S(e[l],t[l],s,o)););return f}for(var c in e)if(bt.call(e,c)&&(l++,!bt.call(t,c)||!S(e[c],t[c],s,o)))return i;for(c in t)if(bt.call(t,c)&&!(l--))return i;if(qt)for(;7>++u;)if(c= -dt[u],bt.call(e,c)&&(!bt.call(t,c)||!S(e[c],t[c],s,o)))return i;return n}function x(e){return"function"==typeof e}function T(e){return e?Yt[typeof e]:i}function N(e){return xt.call(e)==It}function C(e,t,n){var i=arguments,s=0,o=2,u=i[3],a=i[4];n!==Y&&(u=[],a=[],"number"!=typeof n&&(o=i.length));for(;++sn?At(0,s+n):n)||0;return"number"==typeof s?o=-1<(N(e)?e.indexOf(t,n):q(e,t,n)):pn(e,function(e){if(++r>=n)return!(o=e===t)}),o}function A(e,t,r){var i=n,t=l(t,r);if(ln(e))for(var r=-1,s=e.length;++rr&&(r=n,o=e)});else for(;++io&&(o=e[i]);return o}function P(e,t){var n=[];return pn(e,function(e){n.push(e[t])}),n}function H(e,t,n,r){var s=3>arguments.length,t=l(t,r);return pn(e,function(e,r,o){n=s?(s=i,e):t(n,e,r,o)}),n}function B(e,t,n,r){var s=e,o=e?e.length:0,u=3>arguments.length;if("number"!=typeof o)var a=hn(e),o=a.length;else Vt&&N(e)&&(s=e.split(""));return pn(e,function(e,f,l){f=a?a[--o]:--o,n=u?(u=i,s[f]):t.call(r,n,s[f],f,l)}),n}function j(e,t,n){var r,t=l(t,n);if(ln(e))for(var n=-1,i=e.length;++nn?At(0,i+n):n||0)-1;else if(n)return r=U(e,t),e[r]===t?r:-1;for(;++r>>1,n(e[r])q(a,h))(n||f)&&a.push(h),u.push(r)}return u}function W(e,t){return Kt||Tt&&2|{(\/]|\[\D|\b(?:delete|in|instanceof|new|typeof|void)\b/,nt=/&(?:amp|lt|gt|quot|#x27);/g,rt=/\b__p\+='';/g,it=/\b(__p\+=)''\+/g,st=/(__e\(.*?\)|\b__t\))\+'';/g -,ot=/\w*$/,ut=/(?:__e|__t=)\(\s*(?![\d\s"']|this\.)/g,at=RegExp("^"+(Q.valueOf+"").replace(/[.*+?^=!:${}()|[\]\/\\]/g,"\\$&").replace(/valueOf|for [^\]]+/g,".+?")+"$"),ft=/\$\{((?:(?=\\?)\\?[\s\S])*?)}/g,lt=/<%=([\s\S]+?)%>/g,ct=/($^)/,ht=/[&<>"']/g,pt=/['\n\r\t\u2028\u2029\\]/g,dt="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" "),vt=Math.ceil,mt=K.concat,gt=Math.floor,yt=at.test(yt=Object.getPrototypeOf)&&yt,bt=Q.hasOwnProperty,wt=K.push,Et= -Q.propertyIsEnumerable,St=K.slice,xt=Q.toString,Tt=at.test(Tt=St.bind)&&Tt,Nt=at.test(Nt=Array.isArray)&&Nt,Ct=e.isFinite,kt=e.isNaN,Lt=at.test(Lt=Object.keys)&&Lt,At=Math.max,Ot=Math.min,Mt=Math.random,_t="[object Arguments]",Dt="[object Array]",Pt="[object Boolean]",Ht="[object Date]",Bt="[object Number]",jt="[object Object]",Ft="[object RegExp]",It="[object String]",qt,Rt,Ut=(Ut={0:1,length:1},K.splice.call(Ut,0,1),Ut[0]),zt=n;(function(){function e(){this.x=1}var t=[];e.prototype={valueOf:1,y -:1};for(var n in new e)t.push(n);for(n in arguments)zt=!n;qt=!/valueOf/.test(t),Rt="x"!=t[0]})(1);var Wt=!m(arguments),Xt="x"!=St.call("x")[0],Vt="xx"!="x"[0]+Object("x")[0];try{var $t=("[object Object]",xt.call(e.document||0)==jt)}catch(Jt){}var Kt=Tt&&/\n|Opera/.test(Tt+xt.call(e.opera)),Qt=Lt&&/^.+$|true/.test(Lt+!!e.attachEvent),Gt={};Gt[_t]=Gt["[object Function]"]=i,Gt[Dt]=Gt[Pt]=Gt[Ht]=Gt[Bt]=Gt[jt]=Gt[Ft]=Gt[It]=n;var Yt={"boolean":i,"function":n,object:n,number:i,string:i,"undefined":i},Zt= -{"\\":"\\","'":"'","\n":"n","\r":"r"," ":"t","\u2028":"u2028","\u2029":"u2029"};s.templateSettings={escape:/<%-([\s\S]+?)%>/g,evaluate:/<%([\s\S]+?)%>/g,interpolate:lt,variable:""};var en={a:"o,v,g",k:"for(var a=1,b=typeof g=='number'?2:arguments.length;a":">",'"':""","'":"'"},an=E(un),fn=c(en,{g:"if(t[i]==null)"+en.g}),ln=Nt||function(e){return xt.call(e)==Dt};x(/x/)&&(x=function(e){return"[object Function]"==xt.call(e)});var cn=yt?function(e){if(!e||"object"!=typeof e)return i;var t=e.valueOf,n="function"==typeof t&&(n=yt(t))&&yt(n);return n?e==n||yt(e)==n&&!m(e):g(e)}:g,hn=Lt?function(e){return"function"==typeof e&&Et.call(e,"prototype")?y(e):T(e)?Lt(e):[]}:y,pn=c(tn);s.VERSION="0.10.0",s.assign=rn,s -.after=function(e,t){return 1>e?t():function(){if(1>--e)return t.apply(this,arguments)}},s.bind=W,s.bindAll=function(e){for(var t=arguments,n=1q(i,e)){for(var s=n;--s;)if(!(r[s]||(r[s]=o(t[s])))(e))return;i.push(e)}}),i},s.invert=E,s.invoke=function(e,t){var n=St.call(arguments,2),r="function"==typeof t,i=[];return pn(e,function(e){i.push((r?t:e[t]).apply(e,n))}),i},s.isArguments=m,s.isArray=ln,s.isBoolean= -function(e){return e===n||e===i||xt.call(e)==Pt},s.isDate=function(e){return xt.call(e)==Ht},s.isElement=function(e){return e?1===e.nodeType:i},s.isEmpty=function(e){var t=n;if(!e)return t;var r=xt.call(e),s=e.length;return r==Dt||r==It||r==_t||Wt&&m(e)||r==jt&&"number"==typeof s&&x(e.splice)?!s:(on(e,function(){return t=i}),t)},s.isEqual=S,s.isFinite=function(e){return Ct(e)&&!kt(parseFloat(e))},s.isFunction=x,s.isNaN=function(e){return xt.call(e)==Bt&&e!=+e},s.isNull=function(e){return e===r},s -.isNumber=function(e){return xt.call(e)==Bt},s.isObject=T,s.isPlainObject=cn,s.isRegExp=function(e){return xt.call(e)==Ft},s.isString=N,s.isUndefined=function(e){return e===t},s.keys=hn,s.last=function(e,t,n){if(e){var i=e.length;return t==r||n?e[i-1]:St.call(e,-t||i)}},s.lastIndexOf=function(e,t,n){var r=e?e.length:0;for("number"==typeof n&&(r=(0>n?At(0,r+n):Ot(n,r-1))+1);r--;)if(e[r]===t)return r;return-1},s.map=_,s.max=D,s.memoize=function(e,t){var n={};return function(){var r=t?t.apply(this,arguments -):arguments[0];return bt.call(n,r)?n[r]:n[r]=e.apply(this,arguments)}},s.merge=C,s.min=function(e,t,n){var r=Infinity,i=-1,s=e?e.length:0,o=r;if(t||!ln(e))t=!t&&N(e)?u:l(t,n),pn(e,function(e,n,i){n=t(e,n,i),nq(s,n,1))i[n]=e}),i},s.once=function(e){var t,s=i;return function(){return s?t:(s=n,t=e.apply(this,arguments),e=r,t)}},s.pairs=function(e){var t=[];return on(e,function(e,n){t.push([n,e])}),t},s.partial=function(e){return f(e,St.call(arguments,1))},s.pick=function(e,t,n){var r={};if("function"!=typeof t)for(var i=0,s=mt.apply(K,arguments),o=s.length;++i=f?(clearTimeout(u),a=r,s=e.apply(o,i) -):u||(u=setTimeout(n,f)),s}},s.times=function(e,t,n){for(var e=+e||0,r=-1,i=Array(e);++r=(n||it);if(i)for(var s={},n=t-1;++nt||"undefined"==typeof e)return 1;if(ei;i++)r+="i='"+e.j[i]+"';if(","constructor"==e.j[i]&&(r+="!(f&&f.prototype===l)&&"),r+="h.call(l,i)){"+e.g+"}"}if(e.b||e.h)r+="}";return r+=e.c+";return t" +,o("e,h,j,k,p,n,s","return function("+t+"){"+r+"}")(c,Tt,b,A,on,_t,Ct)}function p(e){return"\\"+un[e]}function d(e){return dn[e]}function v(e){return"function"!=typeof e.toString&&"string"==typeof (e+"")}function m(){}function g(e,t,n){t||(t=0),"undefined"==typeof n&&(n=e?e.length:0);for(var r=-1,n=n-t||0,i=Array(0>n?0:n);++rn?Dt(0,s+n):n)||0;return"number"==typeof s?o=-1<(A(e)?e.indexOf(t,n):W(e,t,n)):wn(e,function(e){if(++r>=n)return!(o=e===t)}),o}function D(e,t,r){var i=n,t=c +(t,r);if(gn(e))for(var r=-1,s=e.length;++rr&&(r=n,o=e)});else for(;++io&&(o=e[i]);return o}function F(e,t){return B(e,t+"")}function I(e,t,n,r){var s=3>arguments.length;return t||(t=K),wn(e,function(e,o,u){n=s?(s=i,e):t.call(r,n,e,o,u)}),n}function q(e,t,n,r){var s=e,o=e?e.length:0,u=3>arguments.length;if("number"!=typeof o)var a=bn(e),o=a.length;else en&&A(e)&& +(s=e.split(""));return t||(t=K),wn(e,function(e,f,l){f=a?a[--o]:--o,n=u?(u=i,s[f]):t.call(r,n,s[f],f,l)}),n}function R(e,t,n){var r,t=c(t,n);if(gn(e))for(var n=-1,i=e.length;++nn?Dt(0,i+n):n||0)-1;else if(n)return r=V(e,t),e[r]===t?r:-1;for(;++r>>1,n(e[r])W(a,h))(n||f)&&a.push(h),u.push(r)}return u}function J(e,t){return $t||Lt&&2|{(\/]|\[\D|\b(?:delete|in|instanceof|new|typeof|void)\b/,ut=/&(?:amp|lt|gt|quot|#x27);/g,at=/\b__p\+='';/g,ft=/\b(__p\+=)''\+/g,lt=/(__e\(.*?\)|\b__t\))\+'';/g,ct=/\w*$/,ht=/(?:__e|__t=)\(\s*(?![\d\s"']|this\.)/g,pt=RegExp("^"+(tt.valueOf+"").replace(/[.*+?^=!:${}()|[\]\/\\]/g,"\\$&").replace(/valueOf|for [^\]]+/g,".+?")+"$"),dt=/\$\{((?:(?=\\?)\\?[\s\S])*?)}/g,vt=/<%=([\s\S]+?)%>/g,mt=/($^)/,gt=/[&<>"']/g,yt=/['\n\r\t\u2028\u2029\\]/g,bt="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf" +.split(" "),wt=Math.ceil,Et=et.concat,St=Math.floor,xt=pt.test(xt=Object.getPrototypeOf)&&xt,Tt=tt.hasOwnProperty,Nt=et.push,Ct=tt.propertyIsEnumerable,kt=tt.toString,Lt=pt.test(Lt=g.bind)&&Lt,At=pt.test(At=Array.isArray)&&At,Ot=e.isFinite,Mt=e.isNaN,_t=pt.test(_t=Object.keys)&&_t,Dt=Math.max,Pt=Math.min,Ht=Math.random,Bt="[object Arguments]",jt="[object Array]",Ft="[object Boolean]",It="[object Date]",qt="[object Number]",Rt="[object Object]",Ut="[object RegExp]",zt="[object String]",Wt=!/1/.test +(Function("1")),Xt=!!e.attachEvent,Vt=Lt&&!/\n|true/.test(Lt+Xt),$t=Lt&&!Vt,Jt=_t&&(Xt||Vt),Kt,Qt,Gt=(Gt={0:1,length:1},et.splice.call(Gt,0,1),Gt[0]),Yt=n;(function(){function e(){this.x=1}var t=[];e.prototype={valueOf:1,y:1};for(var n in new e)t.push(n);for(n in arguments)Yt=!n;Kt=!/valueOf/.test(t),Qt="x"!=t[0]})(1);var Zt=!b(arguments),en="xx"!="x"[0]+Object("x")[0];try{var tn=("[object Object]",kt.call(document)==Rt)}catch(nn){}var rn={"[object Function]":i};rn[Bt]=rn[jt]=rn[Ft]=rn[It]=rn[qt]= +rn[Rt]=rn[Ut]=rn[zt]=n;var sn={};sn[jt]=Array,sn[Ft]=Boolean,sn[It]=Date,sn[Rt]=Object,sn[qt]=Number,sn[Ut]=RegExp,sn[zt]=String;var on={"boolean":i,"function":n,object:n,number:i,string:i,"undefined":i},un={"\\":"\\","'":"'","\n":"n","\r":"r"," ":"t","\u2028":"u2028","\u2029":"u2029"};s.templateSettings={escape:/<%-([\s\S]+?)%>/g,evaluate:/<%([\s\S]+?)%>/g,interpolate:vt,variable:""};if(Xt||Vt||!Wt)o=Function;var an={a:"o,v,g",k:"for(var a=1,b=typeof g=='number'?2:arguments.length;a":">",'"':""","'":"'"},vn=T(dn),mn=h(an,{g:"if(t[i]==null)"+an.g}),gn=At||function(e){return kt.call(e)==jt};C(/x/)&&(C=function(e){return"[object Function]"==kt.call(e)});var yn=xt?function(e){if(!e||"object"!=typeof +e)return i;var t=e.valueOf,n="function"==typeof t&&(n=xt(t))&&xt(n);return n?e==n||xt(e)==n&&!b(e):w(e)}:w,bn=_t?function(e){return"function"==typeof e&&Ct.call(e,"prototype")?E(e):k(e)?_t(e):[]}:E,wn=h(fn);s.VERSION="1.0.0-rc.1",s.assign=cn,s.after=function(e,t){return 1>e?t():function(){if(1>--e)return t.apply(this,arguments)}},s.bind=J,s.bindAll=function(e){for(var t=arguments,n=1W(i,e)){for(var s=n;--s;)if(! +(r[s]||(r[s]=u(t[s])))(e))return;i.push(e)}}),i},s.invert=T,s.invoke=function(e,t){var n=g(arguments,2),r="function"==typeof t,i=[];return wn(e,function(e){i.push((r?t:e[t]).apply(e,n))}),i},s.isArguments=b,s.isArray=gn,s.isBoolean=function(e){return e===n||e===i||kt.call(e)==Ft},s.isDate=function(e){return kt.call(e)==It},s.isElement=function(e){return e?1===e.nodeType:i},s.isEmpty=function(e){var t=n;if(!e)return t;var r=kt.call(e),s=e.length;return r==jt||r==zt||r==Bt||Zt&&b(e)||r==Rt&&"number"==typeof +s&&C(e.splice)?!s:(pn(e,function(){return t=i}),t)},s.isEqual=N,s.isFinite=function(e){return Ot(e)&&!Mt(parseFloat(e))},s.isFunction=C,s.isNaN=function(e){return L(e)&&e!=+e},s.isNull=function(e){return e===r},s.isNumber=L,s.isObject=k,s.isPlainObject=yn,s.isRegExp=function(e){return kt.call(e)==Ut},s.isString=A,s.isUndefined=function(e){return"undefined"==typeof e},s.keys=bn,s.last=function(e,t,n){if(e){var i=e.length;return t==r||n?e[i-1]:g(e,Dt(0,i-t))}},s.lastIndexOf=function(e,t,n){var r=e? +e.length:0;for("number"==typeof n&&(r=(0>n?Dt(0,r+n):Pt(n,r-1))+1);r--;)if(e[r]===t)return r;return-1},s.map=B,s.max=j,s.memoize=function(e,t){var n={};return function(){var r=t?t.apply(this,arguments):arguments[0];return Tt.call(n,r)?n[r]:n[r]=e.apply(this,arguments)}},s.merge=O,s.min=function(e,t,n){var r=Infinity,i=-1,s=e?e.length:0,o=r;if(t||!gn(e))t=!t&&A(e)?a:c(t,n),wn(e,function(e,n,i){n=t(e,n,i),nW(s,n,1))i[n]=e}),i},s.once=function(e){var t,s=i;return function(){return s?t:(s=n,t=e.apply(this,arguments),e=r,t)}},s.pairs=function(e){var t=[];return pn(e,function(e,n){t.push([n,e])}),t},s.partial=function(e){return l +(e,g(arguments,1))},s.pick=function(e,t,n){var r={};if("function"!=typeof t)for(var i=0,s=Et.apply(et,arguments),o=s.length;++i=l?(clearTimeout(u),u=r,a=f,s=e.apply(o,i)):u||(u=setTimeout(n,l)),s}},s.times=function(e,t,n){for(var e=+e||0,r=-1,i=Array(e);++r + * Build: `lodash underscore -d -o ./lodash.underscore.js` + * (c) 2012 John-David Dalton + * Based on Underscore.js 1.4.2 + * (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc. + * Available under MIT license + */ +;(function(window, undefined) { + + /** Detect free variable `exports` */ + var freeExports = typeof exports == 'object' && exports; + + /** Detect free variable `global` and use it as `window` */ + var freeGlobal = typeof global == 'object' && global; + if (freeGlobal.global === freeGlobal) { + window = freeGlobal; + } + + /** Used for array and object method references */ + var arrayRef = [], + // avoid a Closure Compiler bug by creatively creating an object + objectRef = new function(){}; + + /** Used to generate unique IDs */ + var idCounter = 0; + + /** Used internally to indicate various things */ + var indicatorObject = objectRef; + + /** Used to restore the original `_` reference in `noConflict` */ + var oldDash = window._; + + /** Used to detect template delimiter values that require a with-statement */ + var reComplexDelimiter = /[-?+=!~*%&^<>|{(\/]|\[\D|\b(?:delete|in|instanceof|new|typeof|void)\b/; + + /** Used to match HTML entities */ + var reEscapedHtml = /&(?:amp|lt|gt|quot|#x27);/g; + + /** Used to match empty string literals in compiled template source */ + var reEmptyStringLeading = /\b__p \+= '';/g, + reEmptyStringMiddle = /\b(__p \+=) '' \+/g, + reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; + + /** Used to match regexp flags from their coerced string values */ + var reFlags = /\w*$/; + + /** Used to insert the data object variable into compiled template source */ + var reInsertVariable = /(?:__e|__t = )\(\s*(?![\d\s"']|this\.)/g; + + /** Used to detect if a method is native */ + var reNative = RegExp('^' + + (objectRef.valueOf + '') + .replace(/[.*+?^=!:${}()|[\]\/\\]/g, '\\$&') + .replace(/valueOf|for [^\]]+/g, '.+?') + '$' + ); + + /** + * Used to match ES6 template delimiters + * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-7.8.6 + */ + var reEsTemplate = /\$\{((?:(?=\\?)\\?[\s\S])*?)}/g; + + /** Used to match "interpolate" template delimiters */ + var reInterpolate = /<%=([\s\S]+?)%>/g; + + /** Used to ensure capturing order of template delimiters */ + var reNoMatch = /($^)/; + + /** Used to match HTML characters */ + var reUnescapedHtml = /[&<>"']/g; + + /** Used to match unescaped characters in compiled string literals */ + var reUnescapedString = /['\n\r\t\u2028\u2029\\]/g; + + /** Used to fix the JScript [[DontEnum]] bug */ + var shadowed = [ + 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', + 'toLocaleString', 'toString', 'valueOf' + ]; + + /** Used to make template sourceURLs easier to identify */ + var templateCounter = 0; + + /** Native method shortcuts */ + var ceil = Math.ceil, + concat = arrayRef.concat, + floor = Math.floor, + getPrototypeOf = reNative.test(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf, + hasOwnProperty = objectRef.hasOwnProperty, + push = arrayRef.push, + propertyIsEnumerable = objectRef.propertyIsEnumerable, + toString = objectRef.toString; + + /* Native method shortcuts for methods with the same name as other `lodash` methods */ + var nativeBind = reNative.test(nativeBind = slice.bind) && nativeBind, + nativeIsArray = reNative.test(nativeIsArray = Array.isArray) && nativeIsArray, + nativeIsFinite = window.isFinite, + nativeIsNaN = window.isNaN, + nativeKeys = reNative.test(nativeKeys = Object.keys) && nativeKeys, + nativeMax = Math.max, + nativeMin = Math.min, + nativeRandom = Math.random; + + /** `Object#toString` result shortcuts */ + var argsClass = '[object Arguments]', + arrayClass = '[object Array]', + boolClass = '[object Boolean]', + dateClass = '[object Date]', + funcClass = '[object Function]', + numberClass = '[object Number]', + objectClass = '[object Object]', + regexpClass = '[object RegExp]', + stringClass = '[object String]'; + + /** Detect various environments */ + var isIeOpera = !!window.attachEvent, + isV8 = nativeBind && !/\n|true/.test(nativeBind + isIeOpera); + + /* Detect if `Function#bind` exists and is inferred to be fast (all but V8) */ + var isBindFast = nativeBind && !isV8; + + /** + * Detect if `Array#shift` and `Array#splice` augment array-like objects + * incorrectly: + * + * Firefox < 10, IE compatibility mode, and IE < 9 have buggy Array `shift()` + * and `splice()` functions that fail to remove the last element, `value[0]`, + * of array-like objects even though the `length` property is set to `0`. + * The `shift()` method is buggy in IE 8 compatibility mode, while `splice()` + * is buggy regardless of mode in IE < 9 and buggy in compatibility mode in IE 9. + */ + var hasObjectSpliceBug = (hasObjectSpliceBug = { '0': 1, 'length': 1 }, + arrayRef.splice.call(hasObjectSpliceBug, 0, 1), hasObjectSpliceBug[0]); + + + /** + * Detect lack of support for accessing string characters by index: + * + * IE < 8 can't access characters by index and IE 8 can only access + * characters by index on string literals. + */ + var noCharByIndex = ('x'[0] + Object('x')[0]) != 'xx'; + + /** + * Detect if sourceURL syntax is usable without erroring: + * + * The JS engine embedded in Adobe products will throw a syntax error when + * it encounters a single line comment beginning with the `@` symbol. + * + * The JS engine in Narwhal will generate the function `function anonymous(){//}` + * and throw a syntax error. + * + * Avoid comments beginning `@` symbols in IE because they are part of its + * non-standard conditional compilation support. + * http://msdn.microsoft.com/en-us/library/121hztk3(v=vs.94).aspx + */ + try { + var useSourceURL = (Function('//@')(), !isIeOpera); + } catch(e) { } + + /** Used to determine if values are of the language type Object */ + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + /** Used to escape characters for inclusion in compiled string literals */ + var stringEscapes = { + '\\': '\\', + "'": "'", + '\n': 'n', + '\r': 'r', + '\t': 't', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; + + /*--------------------------------------------------------------------------*/ + + /** + * The `lodash` function. + * + * @name _ + * @constructor + * @category Chaining + * @param {Mixed} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns a `lodash` instance. + */ + function lodash(value) { + // exit early if already wrapped, even if wrapped by a different `lodash` constructor + if (value && typeof value == 'object' && value.__wrapped__) { + return value; + } + // allow invoking `lodash` without the `new` operator + if (!(this instanceof lodash)) { + return new lodash(value); + } + this.__wrapped__ = value; + } + + /** + * By default, the template delimiters used by Lo-Dash are similar to those in + * embedded Ruby (ERB). Change the following template settings to use alternative + * delimiters. + * + * @static + * @memberOf _ + * @type Object + */ + lodash.templateSettings = { + + /** + * Used to detect `data` property values to be HTML-escaped. + * + * @static + * @memberOf _.templateSettings + * @type RegExp + */ + 'escape': /<%-([\s\S]+?)%>/g, + + /** + * Used to detect code to be evaluated. + * + * @static + * @memberOf _.templateSettings + * @type RegExp + */ + 'evaluate': /<%([\s\S]+?)%>/g, + + /** + * Used to detect `data` property values to inject. + * + * @static + * @memberOf _.templateSettings + * @type RegExp + */ + 'interpolate': reInterpolate, + + /** + * Used to reference the data object in the template text. + * + * @static + * @memberOf _.templateSettings + * @type String + */ + 'variable': '' + }; + + /*--------------------------------------------------------------------------*/ + /** Reusable iterator options for `assign` and `defaults` */ + var assignIteratorOptions = { + 'args': 'object, source, guard', + 'top': + "for (var argsIndex = 1, argsLength = typeof guard == 'number' ? 2 : arguments.length; argsIndex < argsLength; argsIndex++) {\n" + + ' if ((iteratee = arguments[argsIndex])) {', + 'objectLoop': 'result[index] = iteratee[index]', + 'bottom': ' }\n}' + }; + + /** + * Reusable iterator options shared by `forEach`, `forIn`, and `forOwn`. + */ + var forEachIteratorOptions = { + 'args': 'collection, callback, thisArg', + 'top': "callback = callback && typeof thisArg == 'undefined' ? callback : createCallback(callback, thisArg)", + 'arrayLoop': 'if (callback(iteratee[index], index, collection) === false) return result', + 'objectLoop': 'if (callback(iteratee[index], index, collection) === false) return result' + }; + + /** Reusable iterator options for `forIn` and `forOwn` */ + var forOwnIteratorOptions = { + 'arrayLoop': null + }; + + /*--------------------------------------------------------------------------*/ + + /** + * Used by `_.max` and `_.min` as the default `callback` when a given + * `collection` is a string value. + * + * @private + * @param {String} value The character to inspect. + * @returns {Number} Returns the code unit of given character. + */ + function charAtCallback(value) { + return value.charCodeAt(0); + } + + /** + * Used by `sortBy` to compare transformed `collection` values, stable sorting + * them in ascending order. + * + * @private + * @param {Object} a The object to compare to `b`. + * @param {Object} b The object to compare to `a`. + * @returns {Number} Returns the sort order indicator of `1` or `-1`. + */ + function compareAscending(a, b) { + var ai = a.index, + bi = b.index; + + a = a.criteria; + b = b.criteria; + + // ensure a stable sort in V8 and other engines + // http://code.google.com/p/v8/issues/detail?id=90 + if (a !== b) { + if (a > b || typeof a == 'undefined') { + return 1; + } + if (a < b || typeof b == 'undefined') { + return -1; + } + } + return ai < bi ? -1 : 1; + } + + /** + * Creates a function that, when called, invokes `func` with the `this` + * binding of `thisArg` and prepends any `partailArgs` to the arguments passed + * to the bound function. + * + * @private + * @param {Function|String} func The function to bind or the method name. + * @param {Mixed} [thisArg] The `this` binding of `func`. + * @param {Array} partialArgs An array of arguments to be partially applied. + * @returns {Function} Returns the new bound function. + */ + function createBound(func, thisArg, partialArgs) { + function bound() { + // `Function#bind` spec + // http://es5.github.com/#x15.3.4.5 + var args = arguments, + thisBinding = thisArg; + + if (partialArgs.length) { + args = args.length + ? partialArgs.concat(slice(args)) + : partialArgs; + } + if (this instanceof bound) { + // ensure `new bound` is an instance of `bound` and `func` + noop.prototype = func.prototype; + thisBinding = new noop; + noop.prototype = null; + + // mimic the constructor's `return` behavior + // http://es5.github.com/#x13.2.2 + var result = func.apply(thisBinding, args); + return isObject(result) ? result : thisBinding; + } + return func.apply(thisBinding, args); + } + return bound; + } + + /** + * Produces an iteration callback bound to an optional `thisArg`. If `func` is + * a property name, the callback will return the property value for a given element. + * + * @private + * @param {Function|String} [func=identity|property] The function called per + * iteration or property name to query. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Function} Returns a callback function. + */ + function createCallback(func, thisArg) { + if (!func) { + return identity; + } + if (typeof func != 'function') { + return function(object) { + return object[func]; + }; + } + if (typeof thisArg != 'undefined') { + return function(value, index, object) { + return func.call(thisArg, value, index, object); + }; + } + return func; + } + + /** + * Creates compiled iteration functions. + * + * @private + * @param {Object} [options1, options2, ...] The compile options object(s). + * useHas - A boolean to specify using `hasOwnProperty` checks in the object loop. + * args - A string of comma separated arguments the iteration function will accept. + * top - A string of code to execute before the iteration branches. + * arrayLoop - A string of code to execute in the array loop. + * objectLoop - A string of code to execute in the object loop. + * bottom - A string of code to execute after the iteration branches. + * + * @returns {Function} Returns the compiled function. + */ + function createIterator() { + var data = { + 'arrayLoop': '', + 'bottom': '', + 'hasDontEnumBug': hasDontEnumBug, + 'objectLoop': '', + 'noArgsEnum': noArgsEnum, + 'noCharByIndex': noCharByIndex, + 'shadowed': shadowed, + 'top': '', + 'useHas': true + }; + + // merge options into a template data object + for (var object, index = 0; object = arguments[index]; index++) { + for (var key in object) { + data[key] = object[key]; + } + } + var args = data.args; + data.firstArg = /^[^,]+/.exec(args)[0]; + + // create the function factory + var factory = Function( + 'createCallback, hasOwnProperty, isString, objectTypes, ' + + 'nativeKeys, propertyIsEnumerable', + 'return function(' + args + ') {\n' + (data) + '\n}' + ); + // return the compiled function + return factory( + createCallback, hasOwnProperty, isString, objectTypes, + nativeKeys, propertyIsEnumerable + ); + } + + /** + * Used by `template` to escape characters for inclusion in compiled + * string literals. + * + * @private + * @param {String} match The matched character to escape. + * @returns {String} Returns the escaped character. + */ + function escapeStringChar(match) { + return '\\' + stringEscapes[match]; + } + + /** + * Used by `escape` to convert characters to HTML entities. + * + * @private + * @param {String} match The matched character to escape. + * @returns {String} Returns the escaped character. + */ + function escapeHtmlChar(match) { + return htmlEscapes[match]; + } + + /** + * Checks if `value` is a DOM node in IE < 9. + * + * @private + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true` if the `value` is a DOM node, else `false`. + */ + function isNode(value) { + // IE < 9 presents DOM nodes as `Object` objects except they have `toString` + // methods that are `typeof` "string" and still can coerce nodes to strings + return typeof value.toString != 'function' && typeof (value + '') == 'string'; + } + + /** + * A no-operation function. + * + * @private + */ + function noop() { + // no operation performed + } + + /** + * Slices the `collection` from the `start` index up to, but not including, + * the `end` index. + * + * Note: This function is used, instead of `Array#slice`, to support node lists + * in IE < 9 and to ensure dense arrays are returned. + * + * @private + * @param {Array|Object|String} collection The collection to slice. + * @param {Number} start The start index. + * @param {Number} end The end index. + * @returns {Array} Returns the new array. + */ + function slice(array, start, end) { + start || (start = 0); + if (typeof end == 'undefined') { + end = array ? array.length : 0; + } + var index = -1, + length = end - start || 0, + result = Array(length < 0 ? 0 : length); + + while (++index < length) { + result[index] = array[start + index]; + } + return result; + } + + /** + * Used by `unescape` to convert HTML entities to characters. + * + * @private + * @param {String} match The matched character to unescape. + * @returns {String} Returns the unescaped character. + */ + function unescapeHtmlChar(match) { + return htmlUnescapes[match]; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Assigns own enumerable properties of source object(s) to the `destination` + * object. Subsequent sources will overwrite propery assignments of previous + * sources. + * + * @static + * @memberOf _ + * @alias extend + * @category Objects + * @param {Object} object The destination object. + * @param {Object} [source1, source2, ...] The source objects. + * @returns {Object} Returns the destination object. + * @example + * + * _.assign({ 'name': 'moe' }, { 'age': 40 }); + * // => { 'name': 'moe', 'age': 40 } + */ + function assign(object) { + if (!object) { + return object; + } + for (var argsIndex = 1, argsLength = arguments.length; argsIndex < argsLength; argsIndex++) { + var iteratee = arguments[argsIndex]; + if (iteratee) { + for (var key in iteratee) { + object[key] = iteratee[key]; + } + } + } + return object; + } + /** + * Checks if `value` is an `arguments` object. + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true` if the `value` is an `arguments` object, else `false`. + * @example + * + * (function() { return _.isArguments(arguments); })(1, 2, 3); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + lodash.isArguments = function(value) { + return toString.call(value) == argsClass; + } + + // fallback for browsers that can't detect `arguments` objects by [[Class]] + if (!lodash.isArguments(arguments)) { + lodash.isArguments = function(value) { + return value ? hasOwnProperty.call(value, 'callee') : false; + }; + } + + /** + * Iterates over `object`'s own and inherited enumerable properties, executing + * the `callback` for each property. The `callback` is bound to `thisArg` and + * invoked with three arguments; (value, key, object). Callbacks may exit iteration + * early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns `object`. + * @example + * + * function Dog(name) { + * this.name = name; + * } + * + * Dog.prototype.bark = function() { + * alert('Woof, woof!'); + * }; + * + * _.forIn(new Dog('Dagny'), function(value, key) { + * alert(key); + * }); + * // => alerts 'name' and 'bark' (order is not guaranteed) + */ + var forIn = function (collection, callback) { + var index, iteratee = collection, result = collection; + if (!collection) return result; + callback || (callback = identity); + + for (index in iteratee) { + if (callback(iteratee[index], index, collection) === indicatorObject) return result; + } + ; + return result + }; + + /** + * Iterates over an object's own enumerable properties, executing the `callback` + * for each property. The `callback` is bound to `thisArg` and invoked with three + * arguments; (value, key, object). Callbacks may exit iteration early by explicitly + * returning `false`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns `object`. + * @example + * + * _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { + * alert(key); + * }); + * // => alerts '0', '1', and 'length' (order is not guaranteed) + */ + var forOwn = function (collection, callback) { + var index, iteratee = collection, result = collection; + if (!collection) return result; + callback || (callback = identity); + + for (index in iteratee) { + if (hasOwnProperty.call(iteratee, index)) { + if (callback(iteratee[index], index, collection) === indicatorObject) return result; + } + } + ; + return result + }; + + /** + * A fallback implementation of `isPlainObject` that checks if a given `value` + * is an object created by the `Object` constructor, assuming objects created + * by the `Object` constructor have no inherited enumerable properties and that + * there are no `Object.prototype` extensions. + * + * @private + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true` if `value` is a plain object, else `false`. + */ + function shimIsPlainObject(value) { + // avoid non-objects and false positives for `arguments` objects + var result = false; + if (!(value && typeof value == 'object') || isArguments(value)) { + return result; + } + // check that the constructor is `Object` (i.e. `Object instanceof Object`) + var ctor = value.constructor; + if ((!isFunction(ctor)) || ctor instanceof ctor) { + // In most environments an object's own properties are iterated before + // its inherited properties. If the last iterated property is an object's + // own property then there are no inherited enumerable properties. + forIn(value, function(value, key) { + result = key; + }); + return result === false || hasOwnProperty.call(value, result); + } + return result; + } + + /** + * A fallback implementation of `Object.keys` that produces an array of the + * given object's own enumerable property names. + * + * @private + * @param {Object} object The object to inspect. + * @returns {Array} Returns a new array of property names. + */ + function shimKeys(object) { + var result = []; + forOwn(object, function(value, key) { + result.push(key); + }); + return result; + } + + /** + * Used to convert characters to HTML entities: + * + * Though the `>` character is escaped for symmetry, characters like `>` and `/` + * don't require escaping in HTML and have no special meaning unless they're part + * of a tag or an unquoted attribute value. + * http://mathiasbynens.be/notes/ambiguous-ampersands (under "semi-related fun fact") + */ + var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + }; + + /** Used to convert HTML entities to characters */ + var htmlUnescapes = invert(htmlEscapes); + + /*--------------------------------------------------------------------------*/ + + /** + * Creates a clone of `value`. If `deep` is `true`, all nested objects will + * also be cloned, otherwise they will be assigned by reference. Functions and + * DOM nodes are **not** cloned. The enumerable properties of `arguments` objects + * and objects created by constructors other than `Object` are cloned to plain + * `Object` objects. + * + * Note: Lo-Dash's deep clone functionality is loosely based on the structured clone algorithm. + * See http://www.w3.org/TR/html5/common-dom-interfaces.html#internal-structured-cloning-algorithm. + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} value The value to clone. + * @param {Boolean} deep A flag to indicate a deep clone. + * @param- {Object} [guard] Internally used to allow this method to work with + * others like `_.map` without using their callback `index` argument for `deep`. + * @param- {Array} [stackA=[]] Internally used to track traversed source objects. + * @param- {Array} [stackB=[]] Internally used to associate clones with their + * source counterparts. + * @returns {Mixed} Returns the cloned `value`. + * @example + * + * var stooges = [ + * { 'name': 'moe', 'age': 40 }, + * { 'name': 'larry', 'age': 50 }, + * { 'name': 'curly', 'age': 60 } + * ]; + * + * _.clone({ 'name': 'moe' }); + * // => { 'name': 'moe' } + * + * var shallow = _.clone(stooges); + * shallow[0] === stooges[0]; + * // => true + * + * var deep = _.clone(stooges, true); + * deep[0] === stooges[0]; + * // => false + */ + function clone(value) { + return value && objectTypes[typeof value] + ? (isArray(value) ? slice(value) : assign({}, value)) + : value + } + /** + * Assigns own enumerable properties of source object(s) to the `destination` + * object for all `destination` properties that resolve to `null`/`undefined`. + * Once a property is set, additional defaults of the same property will be + * ignored. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The destination object. + * @param {Object} [default1, default2, ...] The default objects. + * @returns {Object} Returns the destination object. + * @example + * + * var iceCream = { 'flavor': 'chocolate' }; + * _.defaults(iceCream, { 'flavor': 'vanilla', 'sprinkles': 'rainbow' }); + * // => { 'flavor': 'chocolate', 'sprinkles': 'rainbow' } + */ + function defaults(object) { + if (!object) { + return object; + } + for (var argsIndex = 1, argsLength = arguments.length; argsIndex < argsLength; argsIndex++) { + var iteratee = arguments[argsIndex]; + if (iteratee) { + for (var key in iteratee) { + if (object[key] == null) { + object[key] = iteratee[key]; + } + } + } + } + return object; + } + /** + * Creates a sorted array of all enumerable properties, own and inherited, + * of `object` that have function values. + * + * @static + * @memberOf _ + * @alias methods + * @category Objects + * @param {Object} object The object to inspect. + * @returns {Array} Returns a new array of property names that have function values. + * @example + * + * _.functions(_); + * // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...] + */ + function functions(object) { + var result = []; + forIn(object, function(value, key) { + if (isFunction(value)) { + result.push(key); + } + }); + return result.sort(); + } + + /** + * Checks if the specified object `property` exists and is a direct property, + * instead of an inherited property. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to check. + * @param {String} property The property to check for. + * @returns {Boolean} Returns `true` if key is a direct property, else `false`. + * @example + * + * _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b'); + * // => true + */ + function has(object, property) { + return object ? hasOwnProperty.call(object, property) : false; + } + + /** + * Creates an object composed of the inverted keys and values of the given `object`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to invert. + * @returns {Object} Returns the created inverted object. + * @example + * + * _.invert({ 'first': 'Moe', 'second': 'Larry', 'third': 'Curly' }); + * // => { 'Moe': 'first', 'Larry': 'second', 'Curly': 'third' } (order is not guaranteed) + */ + function invert(object) { + var result = {}; + forOwn(object, function(value, key) { + result[value] = key; + }); + return result; + } + + /** + * Checks if `value` is an array. + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true` if the `value` is an array, else `false`. + * @example + * + * (function() { return _.isArray(arguments); })(); + * // => false + * + * _.isArray([1, 2, 3]); + * // => true + */ + var isArray = nativeIsArray || function(value) { + return toString.call(value) == arrayClass; + }; + + /** + * Checks if `value` is a boolean (`true` or `false`) value. + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true` if the `value` is a boolean value, else `false`. + * @example + * + * _.isBoolean(null); + * // => false + */ + function isBoolean(value) { + return value === true || value === false || toString.call(value) == boolClass; + } + + /** + * Checks if `value` is a date. + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true` if the `value` is a date, else `false`. + * @example + * + * _.isDate(new Date); + * // => true + */ + function isDate(value) { + return toString.call(value) == dateClass; + } + + /** + * Checks if `value` is a DOM element. + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true` if the `value` is a DOM element, else `false`. + * @example + * + * _.isElement(document.body); + * // => true + */ + function isElement(value) { + return value ? value.nodeType === 1 : false; + } + + /** + * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a + * length of `0` and objects with no own enumerable properties are considered + * "empty". + * + * @static + * @memberOf _ + * @category Objects + * @param {Array|Object|String} value The value to inspect. + * @returns {Boolean} Returns `true` if the `value` is empty, else `false`. + * @example + * + * _.isEmpty([1, 2, 3]); + * // => false + * + * _.isEmpty({}); + * // => true + * + * _.isEmpty(''); + * // => true + */ + function isEmpty(value) { + if (!value) { + return true; + } + if (isArray(value) || isString(value)) { + return !value.length; + } + for (var key in value) { + if (hasOwnProperty.call(value, key)) { + return false; + } + } + return true; + } + /** + * Performs a deep comparison between two values to determine if they are + * equivalent to each other. + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} a The value to compare. + * @param {Mixed} b The other value to compare. + * @param- {Object} [stackA=[]] Internally used track traversed `a` objects. + * @param- {Object} [stackB=[]] Internally used track traversed `b` objects. + * @returns {Boolean} Returns `true` if the values are equvalent, else `false`. + * @example + * + * var moe = { 'name': 'moe', 'luckyNumbers': [13, 27, 34] }; + * var clone = { 'name': 'moe', 'luckyNumbers': [13, 27, 34] }; + * + * moe == clone; + * // => false + * + * _.isEqual(moe, clone); + * // => true + */ + function isEqual(a, b, stackA, stackB) { + // exit early for identical values + if (a === b) { + // treat `+0` vs. `-0` as not equal + return a !== 0 || (1 / a == 1 / b); + } + // a strict comparison is necessary because `null == undefined` + if (a == null || b == null) { + return a === b; + } + // compare [[Class]] names + var className = toString.call(a), + otherName = toString.call(b); + + if (className != otherName) { + return false; + } + switch (className) { + case boolClass: + case dateClass: + // coerce dates and booleans to numbers, dates to milliseconds and booleans + // to `1` or `0`, treating invalid dates coerced to `NaN` as not equal + return +a == +b; + + case numberClass: + // treat `NaN` vs. `NaN` as equal + return a != +a + ? b != +b + // but treat `+0` vs. `-0` as not equal + : (a == 0 ? (1 / a == 1 / b) : a == +b); + + case regexpClass: + case stringClass: + // coerce regexes to strings (http://es5.github.com/#x15.10.6.4) + // treat string primitives and their corresponding object instances as equal + return a == b + ''; + } + var isArr = className == arrayClass; + if (!isArr) { + // unwrap any `lodash` wrapped values + if (a.__wrapped__ || b.__wrapped__) { + return isEqual(a.__wrapped__ || a, b.__wrapped__ || b); + } + // exit for functions and DOM nodes + if (className != objectClass) { + return false; + } + // in older versions of Opera, `arguments` objects have `Array` constructors + var ctorA = a.constructor, + ctorB = b.constructor; + + // non `Object` object instances with different constructors are not equal + if (ctorA != ctorB && !( + isFunction(ctorA) && ctorA instanceof ctorA && + isFunction(ctorB) && ctorB instanceof ctorB + )) { + return false; + } + } + // assume cyclic structures are equal + // the algorithm for detecting cyclic structures is adapted from ES 5.1 + // section 15.12.3, abstract operation `JO` (http://es5.github.com/#x15.12.3) + stackA || (stackA = []); + stackB || (stackB = []); + + var length = stackA.length; + while (length--) { + if (stackA[length] == a) { + return stackB[length] == b; + } + } + var index = -1, + result = true, + size = 0; + + // add `a` and `b` to the stack of traversed objects + stackA.push(a); + stackB.push(b); + + // recursively compare objects and arrays (susceptible to call stack limits) + if (isArr) { + // compare lengths to determine if a deep comparison is necessary + size = a.length; + result = size == b.length; + + if (result) { + // deep compare the contents, ignoring non-numeric properties + while (size--) { + if (!(result = isEqual(a[size], b[size], stackA, stackB))) { + break; + } + } + } + return result; + } + // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` + // which, in this case, is more costly + forIn(a, function(value, key, a) { + if (hasOwnProperty.call(a, key)) { + // count the number of properties. + size++; + // deep compare each property value. + return !(result = hasOwnProperty.call(b, key) && isEqual(value, b[key], stackA, stackB)) && indicatorObject; + } + }); + + if (result) { + // ensure both objects have the same number of properties + forIn(b, function(value, key, b) { + if (hasOwnProperty.call(b, key)) { + // `size` will be `-1` if `b` has more properties than `a` + return !(result = --size > -1) && indicatorObject; + } + }); + } + return result; + } + + /** + * Checks if `value` is, or can be coerced to, a finite number. + * + * Note: This is not the same as native `isFinite`, which will return true for + * booleans and empty strings. See http://es5.github.com/#x15.1.2.5. + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true` if the `value` is a finite number, else `false`. + * @example + * + * _.isFinite(-101); + * // => true + * + * _.isFinite('10'); + * // => true + * + * _.isFinite(true); + * // => false + * + * _.isFinite(''); + * // => false + * + * _.isFinite(Infinity); + * // => false + */ + function isFinite(value) { + return nativeIsFinite(value) && toString.call(value) == numberClass; + } + /** + * Checks if `value` is a function. + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true` if the `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + */ + function isFunction(value) { + return typeof value == 'function'; + } + // fallback for older versions of Chrome and Safari + if (isFunction(/x/)) { + isFunction = function(value) { + return toString.call(value) == funcClass; + }; + } + + /** + * Checks if `value` is the language type of Object. + * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true` if the `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(1); + * // => false + */ + function isObject(value) { + // check if the value is the ECMAScript language type of Object + // http://es5.github.com/#x8 + // and avoid a V8 bug + // http://code.google.com/p/v8/issues/detail?id=2291 + return value ? objectTypes[typeof value] : false; + } + + /** + * Checks if `value` is `NaN`. + * + * Note: This is not the same as native `isNaN`, which will return `true` for + * `undefined` and other values. See http://es5.github.com/#x15.1.2.4. + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true` if the `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ + function isNaN(value) { + // `NaN` as a primitive is the only value that is not equal to itself + // (perform the [[Class]] check first to avoid errors with some host objects in IE) + return isNumber(value) && value != +value + } + + /** + * Checks if `value` is `null`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true` if the `value` is `null`, else `false`. + * @example + * + * _.isNull(null); + * // => true + * + * _.isNull(undefined); + * // => false + */ + function isNull(value) { + return value === null; + } + + /** + * Checks if `value` is a number. + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true` if the `value` is a number, else `false`. + * @example + * + * _.isNumber(8.4 * 5); + * // => true + */ + function isNumber(value) { + return typeof value == 'number' || toString.call(value) == numberClass; + } + + /** + * Checks if `value` is a regular expression. + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true` if the `value` is a regular expression, else `false`. + * @example + * + * _.isRegExp(/moe/); + * // => true + */ + function isRegExp(value) { + return toString.call(value) == regexpClass; + } + + /** + * Checks if `value` is a string. + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true` if the `value` is a string, else `false`. + * @example + * + * _.isString('moe'); + * // => true + */ + function isString(value) { + return typeof value == 'string' || toString.call(value) == stringClass; + } + + /** + * Checks if `value` is `undefined`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true` if the `value` is `undefined`, else `false`. + * @example + * + * _.isUndefined(void 0); + * // => true + */ + function isUndefined(value) { + return typeof value == 'undefined'; + } + + /** + * Creates an array composed of the own enumerable property names of `object`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to inspect. + * @returns {Array} Returns a new array of property names. + * @example + * + * _.keys({ 'one': 1, 'two': 2, 'three': 3 }); + * // => ['one', 'two', 'three'] (order is not guaranteed) + */ + var keys = !nativeKeys ? shimKeys : function(object) { + return (isObject(object) ? nativeKeys(object) : []); + }; + + /** + * Creates a shallow clone of `object` excluding the specified properties. + * Property names may be specified as individual arguments or as arrays of + * property names. If `callback` is passed, it will be executed for each property + * in the `object`, omitting the properties `callback` returns truthy for. The + * `callback` is bound to `thisArg` and invoked with three arguments; (value, key, object). + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The source object. + * @param {Function|String} callback|[prop1, prop2, ...] The properties to omit + * or the function called per iteration. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns an object without the omitted properties. + * @example + * + * _.omit({ 'name': 'moe', 'age': 40, 'userid': 'moe1' }, 'userid'); + * // => { 'name': 'moe', 'age': 40 } + * + * _.omit({ 'name': 'moe', '_hint': 'knucklehead', '_seed': '96c4eb' }, function(value, key) { + * return key.charAt(0) == '_'; + * }); + * // => { 'name': 'moe' } + */ + function omit(object) { + var props = concat.apply(arrayRef, arguments), + result = {}; + + forIn(object, function(value, key) { + if (indexOf(props, key, 1) < 0) { + result[key] = value; + } + }); + return result; + } + /** + * Creates a two dimensional array of the given object's key-value pairs, + * i.e. `[[key1, value1], [key2, value2]]`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to inspect. + * @returns {Array} Returns new array of key-value pairs. + * @example + * + * _.pairs({ 'moe': 30, 'larry': 40, 'curly': 50 }); + * // => [['moe', 30], ['larry', 40], ['curly', 50]] (order is not guaranteed) + */ + function pairs(object) { + var result = []; + forOwn(object, function(value, key) { + result.push([key, value]); + }); + return result; + } + + /** + * Creates a shallow clone of `object` composed of the specified properties. + * Property names may be specified as individual arguments or as arrays of + * property names. If `callback` is passed, it will be executed for each property + * in the `object`, picking the properties `callback` returns truthy for. The + * `callback` is bound to `thisArg` and invoked with three arguments; (value, key, object). + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The source object. + * @param {Function|String} callback|[prop1, prop2, ...] The properties to pick + * or the function called per iteration. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns an object composed of the picked properties. + * @example + * + * _.pick({ 'name': 'moe', 'age': 40, 'userid': 'moe1' }, 'name', 'age'); + * // => { 'name': 'moe', 'age': 40 } + * + * _.pick({ 'name': 'moe', '_hint': 'knucklehead', '_seed': '96c4eb' }, function(value, key) { + * return key.charAt(0) != '_'; + * }); + * // => { 'name': 'moe' } + */ + function pick(object) { + var index = 0, + props = concat.apply(arrayRef, arguments), + length = props.length, + result = {}; + + while (++index < length) { + var prop = props[index]; + if (prop in object) { + result[prop] = object[prop]; + } + } + return result; + } + /** + * Creates an array composed of the own enumerable property values of `object`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to inspect. + * @returns {Array} Returns a new array of property values. + * @example + * + * _.values({ 'one': 1, 'two': 2, 'three': 3 }); + * // => [1, 2, 3] + */ + function values(object) { + var result = []; + forOwn(object, function(value) { + result.push(value); + }); + return result; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Checks if a given `target` element is present in a `collection` using strict + * equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used + * as the offset from the end of the collection. + * + * @static + * @memberOf _ + * @alias include + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Mixed} target The value to check for. + * @param {Number} [fromIndex=0] The index to search from. + * @returns {Boolean} Returns `true` if the `target` element is found, else `false`. + * @example + * + * _.contains([1, 2, 3], 1); + * // => true + * + * _.contains([1, 2, 3], 1, 2); + * // => false + * + * _.contains({ 'name': 'moe', 'age': 40 }, 'moe'); + * // => true + * + * _.contains('curly', 'ur'); + * // => true + */ + function contains(collection, target) { + var length = collection ? collection.length : 0, + result = false; + if (typeof length == 'number') { + result = indexOf(collection, target) > -1; + } else { + forEach(collection, function(value) { + return (result = value === target) && indicatorObject; + }); + } + return result; + } + /** + * Creates an object composed of keys returned from running each element of + * `collection` through a `callback`. The corresponding value of each key is + * the number of times the key was returned by `callback`. The `callback` is + * bound to `thisArg` and invoked with three arguments; (value, index|key, collection). + * The `callback` argument may also be the name of a property to count by (e.g. 'length'). + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Function|String} callback|property The function called per iteration + * or property name to count by. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); }); + * // => { '4': 1, '6': 2 } + * + * _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math); + * // => { '4': 1, '6': 2 } + * + * _.countBy(['one', 'two', 'three'], 'length'); + * // => { '3': 2, '5': 1 } + */ + function countBy(collection, callback, thisArg) { + var result = {}; + callback = createCallback(callback, thisArg); + forEach(collection, function(value, key, collection) { + key = callback(value, key, collection); + (hasOwnProperty.call(result, key) ? result[key]++ : result[key] = 1); + }); + return result; + } + + /** + * Checks if the `callback` returns a truthy value for **all** elements of a + * `collection`. The `callback` is bound to `thisArg` and invoked with three + * arguments; (value, index|key, collection). + * + * @static + * @memberOf _ + * @alias all + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Boolean} Returns `true` if all elements pass the callback check, + * else `false`. + * @example + * + * _.every([true, 1, null, 'yes'], Boolean); + * // => false + */ + function every(collection, callback, thisArg) { + var result = true; + callback = createCallback(callback, thisArg); + + if (isArray(collection)) { + var index = -1, + length = collection.length; + + while (++index < length) { + if (!(result = !!callback(collection[index], index, collection))) { + break; + } + } + } else { + forEach(collection, function(value, index, collection) { + return !(result = !!callback(value, index, collection)) && indicatorObject; + }); + } + return result; + } + + /** + * Examines each element in a `collection`, returning an array of all elements + * the `callback` returns truthy for. The `callback` is bound to `thisArg` and + * invoked with three arguments; (value, index|key, collection). + * + * @static + * @memberOf _ + * @alias select + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new array of elements that passed the callback check. + * @example + * + * var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); + * // => [2, 4, 6] + */ + function filter(collection, callback, thisArg) { + var result = []; + callback = createCallback(callback, thisArg); + + if (isArray(collection)) { + var index = -1, + length = collection.length; + + while (++index < length) { + var value = collection[index]; + if (callback(value, index, collection)) { + result.push(value); + } + } + } else { + forEach(collection, function(value, index, collection) { + if (callback(value, index, collection)) { + result.push(value); + } + }); + } + return result; + } + + /** + * Examines each element in a `collection`, returning the first one the `callback` + * returns truthy for. The function returns as soon as it finds an acceptable + * element, and does not iterate over the entire `collection`. The `callback` is + * bound to `thisArg` and invoked with three arguments; (value, index|key, collection). + * + * @static + * @memberOf _ + * @alias detect + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Mixed} Returns the element that passed the callback check, + * else `undefined`. + * @example + * + * var even = _.find([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); + * // => 2 + */ + function find(collection, callback, thisArg) { + var result; + callback = createCallback(callback, thisArg); + forEach(collection, function(value, index, collection) { + if (callback(value, index, collection)) { + result = value; + return indicatorObject; + } + }); + return result; + } + + /** + * Iterates over a `collection`, executing the `callback` for each element in + * the `collection`. The `callback` is bound to `thisArg` and invoked with three + * arguments; (value, index|key, collection). Callbacks may exit iteration early + * by explicitly returning `false`. + * + * @static + * @memberOf _ + * @alias each + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Array|Object|String} Returns `collection`. + * @example + * + * _([1, 2, 3]).forEach(alert).join(','); + * // => alerts each number and returns '1,2,3' + * + * _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, alert); + * // => alerts each number value (order is not guaranteed) + */ + var forEach = function (collection, callback, thisArg) { + var index, iteratee = collection, result = collection; + if (!collection) return result; + callback = callback && typeof thisArg == 'undefined' ? callback : createCallback(callback, thisArg); + var length = iteratee.length; index = -1; + if (typeof length == 'number') { + while (++index < length) { + if (callback(iteratee[index], index, collection) === indicatorObject) return result + } + } + else { + for (index in iteratee) { + if (hasOwnProperty.call(iteratee, index)) { + if (callback(iteratee[index], index, collection) === indicatorObject) return result; + } + } + } + ; + + }; + + /** + * Creates an object composed of keys returned from running each element of + * `collection` through a `callback`. The corresponding value of each key is an + * array of elements passed to `callback` that returned the key. The `callback` + * is bound to `thisArg` and invoked with three arguments; (value, index|key, collection). + * The `callback` argument may also be the name of a property to group by (e.g. 'length'). + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Function|String} callback|property The function called per iteration + * or property name to group by. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); }); + * // => { '4': [4.2], '6': [6.1, 6.4] } + * + * _.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math); + * // => { '4': [4.2], '6': [6.1, 6.4] } + * + * _.groupBy(['one', 'two', 'three'], 'length'); + * // => { '3': ['one', 'two'], '5': ['three'] } + */ + function groupBy(collection, callback, thisArg) { + var result = {}; + callback = createCallback(callback, thisArg); + forEach(collection, function(value, key, collection) { + key = callback(value, key, collection); + (hasOwnProperty.call(result, key) ? result[key] : result[key] = []).push(value); + }); + return result; + } + + /** + * Invokes the method named by `methodName` on each element in the `collection`, + * returning an array of the results of each invoked method. Additional arguments + * will be passed to each invoked method. If `methodName` is a function it will + * be invoked for, and `this` bound to, each element in the `collection`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Function|String} methodName The name of the method to invoke or + * the function invoked per iteration. + * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the method with. + * @returns {Array} Returns a new array of the results of each invoked method. + * @example + * + * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); + * // => [[1, 5, 7], [1, 2, 3]] + * + * _.invoke([123, 456], String.prototype.split, ''); + * // => [['1', '2', '3'], ['4', '5', '6']] + */ + function invoke(collection, methodName) { + var args = slice(arguments, 2), + isFunc = typeof methodName == 'function', + result = []; + + forEach(collection, function(value) { + result.push((isFunc ? methodName : value[methodName]).apply(value, args)); + }); + return result; + } + + /** + * Creates an array of values by running each element in the `collection` + * through a `callback`. The `callback` is bound to `thisArg` and invoked with + * three arguments; (value, index|key, collection). + * + * @static + * @memberOf _ + * @alias collect + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new array of the results of each `callback` execution. + * @example + * + * _.map([1, 2, 3], function(num) { return num * 3; }); + * // => [3, 6, 9] + * + * _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; }); + * // => [3, 6, 9] (order is not guaranteed) + */ + function map(collection, callback, thisArg) { + var index = -1, + length = collection ? collection.length : 0, + result = Array(typeof length == 'number' ? length : 0); + + callback = createCallback(callback, thisArg); + if (isArray(collection)) { + while (++index < length) { + result[index] = callback(collection[index], index, collection); + } + } else { + forEach(collection, function(value, key, collection) { + result[++index] = callback(value, key, collection); + }); + } + return result; + } + + /** + * Retrieves the maximum value of an `array`. If `callback` is passed, + * it will be executed for each value in the `array` to generate the + * criterion by which the value is ranked. The `callback` is bound to + * `thisArg` and invoked with three arguments; (value, index, collection). + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Function} [callback] The function called per iteration. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Mixed} Returns the maximum value. + * @example + * + * var stooges = [ + * { 'name': 'moe', 'age': 40 }, + * { 'name': 'larry', 'age': 50 }, + * { 'name': 'curly', 'age': 60 } + * ]; + * + * _.max(stooges, function(stooge) { return stooge.age; }); + * // => { 'name': 'curly', 'age': 60 }; + */ + function max(collection, callback, thisArg) { + var computed = -Infinity, + index = -1, + length = collection ? collection.length : 0, + result = computed; + + if (callback || !isArray(collection)) { + callback = createCallback(callback, thisArg); + + forEach(collection, function(value, index, collection) { + var current = callback(value, index, collection); + if (current > computed) { + computed = current; + result = value; + } + }); + } else { + while (++index < length) { + if (collection[index] > result) { + result = collection[index]; + } + } + } + return result; + } + + /** + * Retrieves the minimum value of an `array`. If `callback` is passed, + * it will be executed for each value in the `array` to generate the + * criterion by which the value is ranked. The `callback` is bound to `thisArg` + * and invoked with three arguments; (value, index, collection). + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Function} [callback] The function called per iteration. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Mixed} Returns the minimum value. + * @example + * + * _.min([10, 5, 100, 2, 1000]); + * // => 2 + */ + function min(collection, callback, thisArg) { + var computed = Infinity, + index = -1, + length = collection ? collection.length : 0, + result = computed; + + if (callback || !isArray(collection)) { + callback = createCallback(callback, thisArg); + + forEach(collection, function(value, index, collection) { + var current = callback(value, index, collection); + if (current < computed) { + computed = current; + result = value; + } + }); + } else { + while (++index < length) { + if (collection[index] < result) { + result = collection[index]; + } + } + } + return result; + } + + /** + * Retrieves the value of a specified property from all elements in + * the `collection`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {String} property The property to pluck. + * @returns {Array} Returns a new array of property values. + * @example + * + * var stooges = [ + * { 'name': 'moe', 'age': 40 }, + * { 'name': 'larry', 'age': 50 }, + * { 'name': 'curly', 'age': 60 } + * ]; + * + * _.pluck(stooges, 'name'); + * // => ['moe', 'larry', 'curly'] + */ + function pluck(collection, property) { + return map(collection, property + ''); + } + + /** + * Boils down a `collection` to a single value. The initial state of the + * reduction is `accumulator` and each successive step of it should be returned + * by the `callback`. The `callback` is bound to `thisArg` and invoked with 4 + * arguments; for arrays they are (accumulator, value, index|key, collection). + * + * @static + * @memberOf _ + * @alias foldl, inject + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {Mixed} [accumulator] Initial value of the accumulator. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Mixed} Returns the accumulated value. + * @example + * + * var sum = _.reduce([1, 2, 3], function(memo, num) { return memo + num; }); + * // => 6 + */ + function reduce(collection, callback, accumulator, thisArg) { + var noaccum = arguments.length < 3; + callback || (callback = identity); + forEach(collection, function(value, index, collection) { + accumulator = noaccum + ? (noaccum = false, value) + : callback.call(thisArg, accumulator, value, index, collection) + }); + return accumulator; + } + + /** + * The right-associative version of `_.reduce`. + * + * @static + * @memberOf _ + * @alias foldr + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {Mixed} [accumulator] Initial value of the accumulator. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Mixed} Returns the accumulated value. + * @example + * + * var list = [[0, 1], [2, 3], [4, 5]]; + * var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []); + * // => [4, 5, 2, 3, 0, 1] + */ + function reduceRight(collection, callback, accumulator, thisArg) { + var iteratee = collection, + length = collection ? collection.length : 0, + noaccum = arguments.length < 3; + + if (typeof length != 'number') { + var props = keys(collection); + length = props.length; + } + callback || (callback = identity); + forEach(collection, function(value, index, collection) { + index = props ? props[--length] : --length; + accumulator = noaccum + ? (noaccum = false, iteratee[index]) + : callback.call(thisArg, accumulator, iteratee[index], index, collection); + }); + return accumulator; + } + + /** + * The opposite of `_.filter`, this method returns the values of a + * `collection` that `callback` does **not** return truthy for. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new array of elements that did **not** pass the + * callback check. + * @example + * + * var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); + * // => [1, 3, 5] + */ + function reject(collection, callback, thisArg) { + callback = createCallback(callback, thisArg); + return filter(collection, function(value, index, collection) { + return !callback(value, index, collection); + }); + } + + /** + * Creates an array of shuffled `array` values, using a version of the + * Fisher-Yates shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|String} collection The collection to shuffle. + * @returns {Array} Returns a new shuffled collection. + * @example + * + * _.shuffle([1, 2, 3, 4, 5, 6]); + * // => [4, 1, 6, 3, 5, 2] + */ + function shuffle(collection) { + var index = -1, + result = Array(collection ? collection.length : 0); + + forEach(collection, function(value) { + var rand = floor(nativeRandom() * (++index + 1)); + result[index] = result[rand]; + result[rand] = value; + }); + return result; + } + + /** + * Gets the size of the `collection` by returning `collection.length` for arrays + * and array-like objects or the number of own enumerable properties for objects. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|String} collection The collection to inspect. + * @returns {Number} Returns `collection.length` or number of own enumerable properties. + * @example + * + * _.size([1, 2]); + * // => 2 + * + * _.size({ 'one': 1, 'two': 2, 'three': 3 }); + * // => 3 + * + * _.size('curly'); + * // => 5 + */ + function size(collection) { + var length = collection ? collection.length : 0; + return typeof length == 'number' ? length : keys(collection).length; + } + + /** + * Checks if the `callback` returns a truthy value for **any** element of a + * `collection`. The function returns as soon as it finds passing value, and + * does not iterate over the entire `collection`. The `callback` is bound to + * `thisArg` and invoked with three arguments; (value, index|key, collection). + * + * @static + * @memberOf _ + * @alias any + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Boolean} Returns `true` if any element passes the callback check, + * else `false`. + * @example + * + * _.some([null, 0, 'yes', false], Boolean); + * // => true + */ + function some(collection, callback, thisArg) { + var result; + callback = createCallback(callback, thisArg); + + if (isArray(collection)) { + var index = -1, + length = collection.length; + + while (++index < length) { + if ((result = callback(collection[index], index, collection))) { + break; + } + } + } else { + forEach(collection, function(value, index, collection) { + return (result = callback(value, index, collection)) && indicatorObject; + }); + } + return !!result; + } + + /** + * Creates an array, stable sorted in ascending order by the results of + * running each element of `collection` through a `callback`. The `callback` + * is bound to `thisArg` and invoked with three arguments; (value, index|key, collection). + * The `callback` argument may also be the name of a property to sort by (e.g. 'length'). + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Function|String} callback|property The function called per iteration + * or property name to sort by. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new array of sorted elements. + * @example + * + * _.sortBy([1, 2, 3], function(num) { return Math.sin(num); }); + * // => [3, 1, 2] + * + * _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math); + * // => [3, 1, 2] + * + * _.sortBy(['larry', 'brendan', 'moe'], 'length'); + * // => ['moe', 'larry', 'brendan'] + */ + function sortBy(collection, callback, thisArg) { + var result = []; + callback = createCallback(callback, thisArg); + forEach(collection, function(value, index, collection) { + result.push({ + 'criteria': callback(value, index, collection), + 'index': index, + 'value': value + }); + }); + + var length = result.length; + result.sort(compareAscending); + while (length--) { + result[length] = result[length].value; + } + return result; + } + + /** + * Converts the `collection` to an array. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|String} collection The collection to convert. + * @returns {Array} Returns the new converted array. + * @example + * + * (function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4); + * // => [2, 3, 4] + */ + function toArray(collection) { + var length = collection ? collection.length : 0; + if (typeof length == 'number') { + return slice(collection); + } + return values(collection); + } + + /** + * Examines each element in a `collection`, returning an array of all elements + * that contain the given `properties`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Object} properties The object of property values to filter by. + * @returns {Array} Returns a new array of elements that contain the given `properties`. + * @example + * + * var stooges = [ + * { 'name': 'moe', 'age': 40 }, + * { 'name': 'larry', 'age': 50 }, + * { 'name': 'curly', 'age': 60 } + * ]; + * + * _.where(stooges, { 'age': 40 }); + * // => [{ 'name': 'moe', 'age': 40 }] + */ + function where(collection, properties) { + var props = keys(properties); + return filter(collection, function(object) { + var length = props.length; + while (length--) { + var result = object[props[length]] === properties[props[length]]; + if (!result) { + break; + } + } + return !!result; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** + * Creates an array with all falsey values of `array` removed. The values + * `false`, `null`, `0`, `""`, `undefined` and `NaN` are all falsey. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to compact. + * @returns {Array} Returns a new filtered array. + * @example + * + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] + */ + function compact(array) { + var index = -1, + length = array ? array.length : 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value) { + result.push(value); + } + } + return result; + } + + /** + * Creates an array of `array` elements not present in the other arrays + * using strict equality for comparisons, i.e. `===`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to process. + * @param {Array} [array1, array2, ...] Arrays to check. + * @returns {Array} Returns a new array of `array` elements not present in the + * other arrays. + * @example + * + * _.difference([1, 2, 3, 4, 5], [5, 2, 10]); + * // => [1, 3, 4] + */ + function difference(array) { + var index = -1, + length = array.length, + flattened = concat.apply(arrayRef, arguments), + result = []; + + while (++index < length) { + var value = array[index] + if (indexOf(flattened, value, length) < 0) { + result.push(value); + } + } + return result + } + /** + * Gets the first element of the `array`. Pass `n` to return the first `n` + * elements of the `array`. + * + * @static + * @memberOf _ + * @alias head, take + * @category Arrays + * @param {Array} array The array to query. + * @param {Number} [n] The number of elements to return. + * @param- {Object} [guard] Internally used to allow this method to work with + * others like `_.map` without using their callback `index` argument for `n`. + * @returns {Mixed} Returns the first element, or an array of the first `n` + * elements, of `array`. + * @example + * + * _.first([5, 4, 3, 2, 1]); + * // => 5 + */ + function first(array, n, guard) { + if (array) { + var length = array.length; + return (n == null || guard) + ? array[0] + : slice(array, 0, nativeMin(nativeMax(0, n), length)); + } + } + + /** + * Flattens a nested array (the nesting can be to any depth). If `shallow` is + * truthy, `array` will only be flattened a single level. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to compact. + * @param {Boolean} shallow A flag to indicate only flattening a single level. + * @returns {Array} Returns a new flattened array. + * @example + * + * _.flatten([1, [2], [3, [[4]]]]); + * // => [1, 2, 3, 4]; + * + * _.flatten([1, [2], [3, [[4]]]], true); + * // => [1, 2, 3, [[4]]]; + */ + function flatten(array, shallow) { + var index = -1, + length = array ? array.length : 0, + result = []; + + while (++index < length) { + var value = array[index]; + + // recursively flatten arrays (susceptible to call stack limits) + if (isArray(value)) { + push.apply(result, shallow ? value : flatten(value)); + } else { + result.push(value); + } + } + return result; + } + + /** + * Gets the index at which the first occurrence of `value` is found using + * strict equality for comparisons, i.e. `===`. If the `array` is already + * sorted, passing `true` for `fromIndex` will run a faster binary search. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to search. + * @param {Mixed} value The value to search for. + * @param {Boolean|Number} [fromIndex=0] The index to search from or `true` to + * perform a binary search on a sorted `array`. + * @returns {Number} Returns the index of the matched value or `-1`. + * @example + * + * _.indexOf([1, 2, 3, 1, 2, 3], 2); + * // => 1 + * + * _.indexOf([1, 2, 3, 1, 2, 3], 2, 3); + * // => 4 + * + * _.indexOf([1, 1, 2, 2, 3, 3], 2, true); + * // => 2 + */ + function indexOf(array, value, fromIndex) { + var index = -1, + length = array ? array.length : 0; + + if (typeof fromIndex == 'number') { + index = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0) - 1; + } else if (fromIndex) { + index = sortedIndex(array, value); + return array[index] === value ? index : -1; + } + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; + } + + /** + * Gets all but the last element of `array`. Pass `n` to exclude the last `n` + * elements from the result. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to query. + * @param {Number} [n=1] The number of elements to exclude. + * @param- {Object} [guard] Internally used to allow this method to work with + * others like `_.map` without using their callback `index` argument for `n`. + * @returns {Array} Returns all but the last element, or `n` elements, of `array`. + * @example + * + * _.initial([3, 2, 1]); + * // => [3, 2] + */ + function initial(array, n, guard) { + if (!array) { + return []; + } + var length = array.length; + n = n == null || guard ? 1 : n || 0; + return slice(array, 0, nativeMin(nativeMax(0, length - n), length)); + } + + /** + * Computes the intersection of all the passed-in arrays using strict equality + * for comparisons, i.e. `===`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} [array1, array2, ...] Arrays to process. + * @returns {Array} Returns a new array of unique elements, in order, that are + * present in **all** of the arrays. + * @example + * + * _.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]); + * // => [1, 2] + */ + function intersection(array) { + var args = arguments, + argsLength = args.length, + result = []; + + forEach(array, function(value) { + if (indexOf(result, value) < 0) { + var length = argsLength; + while (--length) { + if (indexOf(args[length], value) < 0) { + return; + } + } + result.push(value); + } + }); + return result; + } + /** + * Gets the last element of the `array`. Pass `n` to return the last `n` + * elements of the `array`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to query. + * @param {Number} [n] The number of elements to return. + * @param- {Object} [guard] Internally used to allow this method to work with + * others like `_.map` without using their callback `index` argument for `n`. + * @returns {Mixed} Returns the last element, or an array of the last `n` + * elements, of `array`. + * @example + * + * _.last([3, 2, 1]); + * // => 1 + */ + function last(array, n, guard) { + if (array) { + var length = array.length; + return (n == null || guard) ? array[length - 1] : slice(array, nativeMax(0, length - n)); + } + } + + /** + * Gets the index at which the last occurrence of `value` is found using strict + * equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used + * as the offset from the end of the collection. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to search. + * @param {Mixed} value The value to search for. + * @param {Number} [fromIndex=array.length-1] The index to search from. + * @returns {Number} Returns the index of the matched value or `-1`. + * @example + * + * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2); + * // => 4 + * + * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3); + * // => 1 + */ + function lastIndexOf(array, value, fromIndex) { + var index = array ? array.length : 0; + if (typeof fromIndex == 'number') { + index = (fromIndex < 0 ? nativeMax(0, index + fromIndex) : nativeMin(fromIndex, index - 1)) + 1; + } + while (index--) { + if (array[index] === value) { + return index; + } + } + return -1; + } + + /** + * Creates an object composed from arrays of `keys` and `values`. Pass either + * a single two dimensional array, i.e. `[[key1, value1], [key2, value2]]`, or + * two arrays, one of `keys` and one of corresponding `values`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} keys The array of keys. + * @param {Array} [values=[]] The array of values. + * @returns {Object} Returns an object composed of the given keys and + * corresponding values. + * @example + * + * _.object(['moe', 'larry', 'curly'], [30, 40, 50]); + * // => { 'moe': 30, 'larry': 40, 'curly': 50 } + */ + function object(keys, values) { + var index = -1, + length = keys ? keys.length : 0, + result = {}; + + while (++index < length) { + var key = keys[index]; + if (values) { + result[key] = values[index]; + } else { + result[key[0]] = key[1]; + } + } + return result; + } + + /** + * Creates an array of numbers (positive and/or negative) progressing from + * `start` up to but not including `stop`. This method is a port of Python's + * `range()` function. See http://docs.python.org/library/functions.html#range. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Number} [start=0] The start of the range. + * @param {Number} end The end of the range. + * @param {Number} [step=1] The value to increment or descrement by. + * @returns {Array} Returns a new range array. + * @example + * + * _.range(10); + * // => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + * + * _.range(1, 11); + * // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + * + * _.range(0, 30, 5); + * // => [0, 5, 10, 15, 20, 25] + * + * _.range(0, -10, -1); + * // => [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] + * + * _.range(0); + * // => [] + */ + function range(start, end, step) { + start = +start || 0; + step = +step || 1; + + if (end == null) { + end = start; + start = 0; + } + // use `Array(length)` so V8 will avoid the slower "dictionary" mode + // http://youtu.be/XAqIpGU8ZZk#t=17m25s + var index = -1, + length = nativeMax(0, ceil((end - start) / step)), + result = Array(length); + + while (++index < length) { + result[index] = start; + start += step; + } + return result; + } + + /** + * The opposite of `_.initial`, this method gets all but the first value of + * `array`. Pass `n` to exclude the first `n` values from the result. + * + * @static + * @memberOf _ + * @alias drop, tail + * @category Arrays + * @param {Array} array The array to query. + * @param {Number} [n=1] The number of elements to exclude. + * @param- {Object} [guard] Internally used to allow this method to work with + * others like `_.map` without using their callback `index` argument for `n`. + * @returns {Array} Returns all but the first element, or `n` elements, of `array`. + * @example + * + * _.rest([3, 2, 1]); + * // => [2, 1] + */ + function rest(array, n, guard) { + return slice(array, (n == null || guard) ? 1 : nativeMax(0, n)); + } + + /** + * Uses a binary search to determine the smallest index at which the `value` + * should be inserted into `array` in order to maintain the sort order of the + * sorted `array`. If `callback` is passed, it will be executed for `value` and + * each element in `array` to compute their sort ranking. The `callback` is + * bound to `thisArg` and invoked with one argument; (value). The `callback` + * argument may also be the name of a property to order by. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to iterate over. + * @param {Mixed} value The value to evaluate. + * @param {Function|String} [callback=identity|property] The function called + * per iteration or property name to order by. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Number} Returns the index at which the value should be inserted + * into `array`. + * @example + * + * _.sortedIndex([20, 30, 50], 40); + * // => 2 + * + * _.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x'); + * // => 2 + * + * var dict = { + * 'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 } + * }; + * + * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { + * return dict.wordToNumber[word]; + * }); + * // => 2 + * + * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { + * return this.wordToNumber[word]; + * }, dict); + * // => 2 + */ + function sortedIndex(array, value, callback, thisArg) { + var low = 0, + high = array ? array.length : low; + + // explicitly reference `identity` for better engine inlining + callback = callback ? createCallback(callback, thisArg) : identity; + value = callback(value); + while (low < high) { + var mid = (low + high) >>> 1; + callback(array[mid]) < value + ? low = mid + 1 + : high = mid; + } + return low; + } + + /** + * Computes the union of the passed-in arrays using strict equality for + * comparisons, i.e. `===`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} [array1, array2, ...] Arrays to process. + * @returns {Array} Returns a new array of unique values, in order, that are + * present in one or more of the arrays. + * @example + * + * _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]); + * // => [1, 2, 3, 101, 10] + */ + function union() { + return uniq(concat.apply(arrayRef, arguments)); + } + + /** + * Creates a duplicate-value-free version of the `array` using strict equality + * for comparisons, i.e. `===`. If the `array` is already sorted, passing `true` + * for `isSorted` will run a faster algorithm. If `callback` is passed, each + * element of `array` is passed through a callback` before uniqueness is computed. + * The `callback` is bound to `thisArg` and invoked with three arguments; (value, index, array). + * + * @static + * @memberOf _ + * @alias unique + * @category Arrays + * @param {Array} array The array to process. + * @param {Boolean} [isSorted=false] A flag to indicate that the `array` is already sorted. + * @param {Function} [callback=identity] The function called per iteration. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a duplicate-value-free array. + * @example + * + * _.uniq([1, 2, 1, 3, 1]); + * // => [1, 2, 3] + * + * _.uniq([1, 1, 2, 2, 3], true); + * // => [1, 2, 3] + * + * _.uniq([1, 2, 1.5, 3, 2.5], function(num) { return Math.floor(num); }); + * // => [1, 2, 3] + * + * _.uniq([1, 2, 1.5, 3, 2.5], function(num) { return this.floor(num); }, Math); + * // => [1, 2, 3] + */ + function uniq(array, isSorted, callback, thisArg) { + var index = -1, + length = array ? array.length : 0, + result = [], + seen = result; + + if (callback) { + seen = []; + callback = createCallback(callback, thisArg); + } + while (++index < length) { + var value = array[index], + computed = callback ? callback(value, index, array) : value; + + if (isSorted + ? !index || seen[seen.length - 1] !== computed + : indexOf(seen, computed) < 0 + ) { + if (callback) { + seen.push(computed); + } + result.push(value); + } + } + return result; + } + /** + * Creates an array with all occurrences of the passed values removed using + * strict equality for comparisons, i.e. `===`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to filter. + * @param {Mixed} [value1, value2, ...] Values to remove. + * @returns {Array} Returns a new filtered array. + * @example + * + * _.without([1, 2, 1, 0, 3, 1, 4], 0, 1); + * // => [2, 3, 4] + */ + function without(array) { + var index = -1, + length = array.length, + result = []; + + while (++index < length) { + var value = array[index] + if (indexOf(arguments, value, 1) < 0) { + result.push(value); + } + } + return result + } + /** + * Groups the elements of each array at their corresponding indexes. Useful for + * separate data sources that are coordinated through matching array indexes. + * For a matrix of nested arrays, `_.zip.apply(...)` can transpose the matrix + * in a similar fashion. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} [array1, array2, ...] Arrays to process. + * @returns {Array} Returns a new array of grouped elements. + * @example + * + * _.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]); + * // => [['moe', 30, true], ['larry', 40, false], ['curly', 50, false]] + */ + function zip(array) { + var index = -1, + length = array ? max(pluck(arguments, 'length')) : 0, + result = Array(length); + + while (++index < length) { + result[index] = pluck(arguments, index); + } + return result; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Creates a function that is restricted to executing `func` only after it is + * called `n` times. The `func` is executed with the `this` binding of the + * created function. + * + * @static + * @memberOf _ + * @category Functions + * @param {Number} n The number of times the function must be called before + * it is executed. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var renderNotes = _.after(notes.length, render); + * _.forEach(notes, function(note) { + * note.asyncSave({ 'success': renderNotes }); + * }); + * // `renderNotes` is run once, after all notes have saved + */ + function after(n, func) { + if (n < 1) { + return func(); + } + return function() { + if (--n < 1) { + return func.apply(this, arguments); + } + }; + } + + /** + * Creates a function that, when called, invokes `func` with the `this` + * binding of `thisArg` and prepends any additional `bind` arguments to those + * passed to the bound function. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to bind. + * @param {Mixed} [thisArg] The `this` binding of `func`. + * @param {Mixed} [arg1, arg2, ...] Arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var func = function(greeting) { + * return greeting + ' ' + this.name; + * }; + * + * func = _.bind(func, { 'name': 'moe' }, 'hi'); + * func(); + * // => 'hi moe' + */ + function bind(func, thisArg) { + // use `Function#bind` if it exists and is fast + // (in V8 `Function#bind` is slower except when partially applied) + return isBindFast || (nativeBind && arguments.length > 2) + ? nativeBind.call.apply(nativeBind, arguments) + : createBound(func, thisArg, slice(arguments, 2)); + } + + /** + * Binds methods on `object` to `object`, overwriting the existing method. + * If no method names are provided, all the function properties of `object` + * will be bound. + * + * @static + * @memberOf _ + * @category Functions + * @param {Object} object The object to bind and assign the bound methods to. + * @param {String} [methodName1, methodName2, ...] Method names on the object to bind. + * @returns {Object} Returns `object`. + * @example + * + * var buttonView = { + * 'label': 'lodash', + * 'onClick': function() { alert('clicked: ' + this.label); } + * }; + * + * _.bindAll(buttonView); + * jQuery('#lodash_button').on('click', buttonView.onClick); + * // => When the button is clicked, `this.label` will have the correct value + */ + function bindAll(object) { + var funcs = arguments, + index = funcs.length > 1 ? 0 : (funcs = functions(object), -1), + length = funcs.length; + + while (++index < length) { + var key = funcs[index]; + object[key] = bind(object[key], object); + } + return object; + } + + /** + * Creates a function that is the composition of the passed functions, + * where each function consumes the return value of the function that follows. + * In math terms, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`. + * Each function is executed with the `this` binding of the composed function. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} [func1, func2, ...] Functions to compose. + * @returns {Function} Returns the new composed function. + * @example + * + * var greet = function(name) { return 'hi: ' + name; }; + * var exclaim = function(statement) { return statement + '!'; }; + * var welcome = _.compose(exclaim, greet); + * welcome('moe'); + * // => 'hi: moe!' + */ + function compose() { + var funcs = arguments; + return function() { + var args = arguments, + length = funcs.length; + + while (length--) { + args = [funcs[length].apply(this, args)]; + } + return args[0]; + }; + } + + /** + * Creates a function that will delay the execution of `func` until after + * `wait` milliseconds have elapsed since the last time it was invoked. Pass + * `true` for `immediate` to cause debounce to invoke `func` on the leading, + * instead of the trailing, edge of the `wait` timeout. Subsequent calls to + * the debounced function will return the result of the last `func` call. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to debounce. + * @param {Number} wait The number of milliseconds to delay. + * @param {Boolean} immediate A flag to indicate execution is on the leading + * edge of the timeout. + * @returns {Function} Returns the new debounced function. + * @example + * + * var lazyLayout = _.debounce(calculateLayout, 300); + * jQuery(window).on('resize', lazyLayout); + */ + function debounce(func, wait, immediate) { + var args, + result, + thisArg, + timeoutId; + + function delayed() { + timeoutId = null; + if (!immediate) { + result = func.apply(thisArg, args); + } + } + return function() { + var isImmediate = immediate && !timeoutId; + args = arguments; + thisArg = this; + + clearTimeout(timeoutId); + timeoutId = setTimeout(delayed, wait); + + if (isImmediate) { + result = func.apply(thisArg, args); + } + return result; + }; + } + + /** + * Executes the `func` function after `wait` milliseconds. Additional arguments + * will be passed to `func` when it is invoked. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to delay. + * @param {Number} wait The number of milliseconds to delay execution. + * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the function with. + * @returns {Number} Returns the `setTimeout` timeout id. + * @example + * + * var log = _.bind(console.log, console); + * _.delay(log, 1000, 'logged later'); + * // => 'logged later' (Appears after one second.) + */ + function delay(func, wait) { + var args = slice(arguments, 2); + return setTimeout(function() { func.apply(undefined, args); }, wait); + } + + /** + * Defers executing the `func` function until the current call stack has cleared. + * Additional arguments will be passed to `func` when it is invoked. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to defer. + * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the function with. + * @returns {Number} Returns the `setTimeout` timeout id. + * @example + * + * _.defer(function() { alert('deferred'); }); + * // returns from the function before `alert` is called + */ + function defer(func) { + var args = slice(arguments, 1); + return setTimeout(function() { func.apply(undefined, args); }, 1); + } + + /** + * Creates a function that memoizes the result of `func`. If `resolver` is + * passed, it will be used to determine the cache key for storing the result + * based on the arguments passed to the memoized function. By default, the first + * argument passed to the memoized function is used as the cache key. The `func` + * is executed with the `this` binding of the memoized function. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] A function used to resolve the cache key. + * @returns {Function} Returns the new memoizing function. + * @example + * + * var fibonacci = _.memoize(function(n) { + * return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); + * }); + */ + function memoize(func, resolver) { + var cache = {}; + return function() { + var key = resolver ? resolver.apply(this, arguments) : arguments[0]; + return hasOwnProperty.call(cache, key) + ? cache[key] + : (cache[key] = func.apply(this, arguments)); + }; + } + + /** + * Creates a function that is restricted to execute `func` once. Repeat calls to + * the function will return the value of the first call. The `func` is executed + * with the `this` binding of the created function. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // Application is only created once. + */ + function once(func) { + var result, + ran = false; + + return function() { + if (ran) { + return result; + } + ran = true; + result = func.apply(this, arguments); + + // clear the `func` variable so the function may be garbage collected + func = null; + return result; + }; + } + + /** + * Creates a function that, when executed, will only call the `func` + * function at most once per every `wait` milliseconds. If the throttled + * function is invoked more than once during the `wait` timeout, `func` will + * also be called on the trailing edge of the timeout. Subsequent calls to the + * throttled function will return the result of the last `func` call. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to throttle. + * @param {Number} wait The number of milliseconds to throttle executions to. + * @returns {Function} Returns the new throttled function. + * @example + * + * var throttled = _.throttle(updatePosition, 100); + * jQuery(window).on('scroll', throttled); + */ + function throttle(func, wait) { + var args, + result, + thisArg, + timeoutId, + lastCalled = 0; + + function trailingCall() { + lastCalled = new Date; + timeoutId = null; + result = func.apply(thisArg, args); + } + return function() { + var now = new Date, + remaining = wait - (now - lastCalled); + + args = arguments; + thisArg = this; + + if (remaining <= 0) { + clearTimeout(timeoutId); + timeoutId = null; + lastCalled = now; + result = func.apply(thisArg, args); + } + else if (!timeoutId) { + timeoutId = setTimeout(trailingCall, remaining); + } + return result; + }; + } + + /** + * Creates a function that passes `value` to the `wrapper` function as its + * first argument. Additional arguments passed to the function are appended + * to those passed to the `wrapper` function. The `wrapper` is executed with + * the `this` binding of the created function. + * + * @static + * @memberOf _ + * @category Functions + * @param {Mixed} value The value to wrap. + * @param {Function} wrapper The wrapper function. + * @returns {Function} Returns the new function. + * @example + * + * var hello = function(name) { return 'hello ' + name; }; + * hello = _.wrap(hello, function(func) { + * return 'before, ' + func('moe') + ', after'; + * }); + * hello(); + * // => 'before, hello moe, after' + */ + function wrap(value, wrapper) { + return function() { + var args = [value]; + push.apply(args, arguments); + return wrapper.apply(this, args); + }; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Converts the characters `&`, `<`, `>`, `"`, and `'` in `string` to their + * corresponding HTML entities. + * + * @static + * @memberOf _ + * @category Utilities + * @param {String} string The string to escape. + * @returns {String} Returns the escaped string. + * @example + * + * _.escape('Moe, Larry & Curly'); + * // => 'Moe, Larry & Curly' + */ + function escape(string) { + return string == null ? '' : (string + '').replace(reUnescapedHtml, escapeHtmlChar); + } + + /** + * This function returns the first argument passed to it. + * + * Note: This function is used throughout Lo-Dash as a default callback. + * + * @static + * @memberOf _ + * @category Utilities + * @param {Mixed} value Any value. + * @returns {Mixed} Returns `value`. + * @example + * + * var moe = { 'name': 'moe' }; + * moe === _.identity(moe); + * // => true + */ + function identity(value) { + return value; + } + + /** + * Adds functions properties of `object` to the `lodash` function and chainable + * wrapper. + * + * @static + * @memberOf _ + * @category Utilities + * @param {Object} object The object of function properties to add to `lodash`. + * @example + * + * _.mixin({ + * 'capitalize': function(string) { + * return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); + * } + * }); + * + * _.capitalize('larry'); + * // => 'Larry' + * + * _('curly').capitalize(); + * // => 'Curly' + */ + function mixin(object) { + forEach(functions(object), function(methodName) { + var func = lodash[methodName] = object[methodName]; + + lodash.prototype[methodName] = function() { + var args = [this.__wrapped__]; + push.apply(args, arguments); + + var result = func.apply(lodash, args); + if (this.__chain__) { + result = new lodash(result); + result.__chain__ = true; + } + return result; + }; + }); + } + + /** + * Reverts the '_' variable to its previous value and returns a reference to + * the `lodash` function. + * + * @static + * @memberOf _ + * @category Utilities + * @returns {Function} Returns the `lodash` function. + * @example + * + * var lodash = _.noConflict(); + */ + function noConflict() { + window._ = oldDash; + return this; + } + + /** + * Produces a random number between `min` and `max` (inclusive). If only one + * argument is passed, a number between `0` and the given number will be returned. + * + * @static + * @memberOf _ + * @category Utilities + * @param {Number} [min=0] The minimum possible value. + * @param {Number} [max=1] The maximum possible value. + * @returns {Number} Returns a random number. + * @example + * + * _.random(0, 5); + * // => a number between 1 and 5 + * + * _.random(5); + * // => also a number between 1 and 5 + */ + function random(min, max) { + if (min == null && max == null) { + max = 1; + } + min = +min || 0; + if (max == null) { + max = min; + min = 0; + } + return min + floor(nativeRandom() * ((+max || 0) - min + 1)); + } + + /** + * Resolves the value of `property` on `object`. If `property` is a function + * it will be invoked and its result returned, else the property value is + * returned. If `object` is falsey, then `null` is returned. + * + * @static + * @memberOf _ + * @category Utilities + * @param {Object} object The object to inspect. + * @param {String} property The property to get the value of. + * @returns {Mixed} Returns the resolved value. + * @example + * + * var object = { + * 'cheese': 'crumpets', + * 'stuff': function() { + * return 'nonsense'; + * } + * }; + * + * _.result(object, 'cheese'); + * // => 'crumpets' + * + * _.result(object, 'stuff'); + * // => 'nonsense' + */ + function result(object, property) { + // based on Backbone's private `getValue` function + // https://github.com/documentcloud/backbone/blob/0.9.2/backbone.js#L1419-1424 + var value = object ? object[property] : null; + return isFunction(value) ? object[property]() : value; + } + + /** + * A micro-templating method that handles arbitrary delimiters, preserves + * whitespace, and correctly escapes quotes within interpolated code. + * + * Note: In the development build `_.template` utilizes sourceURLs for easier + * debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl + * + * Note: Lo-Dash may be used in Chrome extensions by either creating a `lodash csp` + * build and avoiding `_.template` use, or loading Lo-Dash in a sandboxed page. + * See http://developer.chrome.com/trunk/extensions/sandboxingEval.html + * + * @static + * @memberOf _ + * @category Utilities + * @param {String} text The template text. + * @param {Obect} data The data object used to populate the text. + * @param {Object} options The options object. + * escape - The "escape" delimiter regexp. + * evaluate - The "evaluate" delimiter regexp. + * interpolate - The "interpolate" delimiter regexp. + * sourceURL - The sourceURL of the template's compiled source. + * variable - The data object variable name. + * + * @returns {Function|String} Returns a compiled function when no `data` object + * is given, else it returns the interpolated text. + * @example + * + * // using a compiled template + * var compiled = _.template('hello <%= name %>'); + * compiled({ 'name': 'moe' }); + * // => 'hello moe' + * + * var list = '<% _.forEach(people, function(name) { %>
  • <%= name %>
  • <% }); %>'; + * _.template(list, { 'people': ['moe', 'larry', 'curly'] }); + * // => '
  • moe
  • larry
  • curly
  • ' + * + * // using the "escape" delimiter to escape HTML in data property values + * _.template('<%- value %>', { 'value': '