diff --git a/.gitignore b/.gitignore index 37a7af5c7d..87adb6951b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ *.custom.* .DS_Store dist/ -node_modules/ \ No newline at end of file +node_modules/ diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index ddd6fc35d8..0000000000 --- a/.gitmodules +++ /dev/null @@ -1,24 +0,0 @@ -[submodule "vendor/benchmark.js"] - path = vendor/benchmark.js - url = git://github.com/bestiejs/benchmark.js.git -[submodule "vendor/docdown"] - path = vendor/docdown - url = git://github.com/jdalton/docdown.git -[submodule "vendor/qunit"] - path = vendor/qunit - url = git://github.com/jquery/qunit.git -[submodule "vendor/qunit-clib"] - path = vendor/qunit-clib - url = git://github.com/jdalton/qunit-clib.git -[submodule "vendor/requirejs"] - path = vendor/requirejs - url = git://github.com/jrburke/requirejs.git -[submodule "vendor/uglifyjs"] - path = vendor/uglifyjs - url = git://github.com/mishoo/UglifyJS.git -[submodule "vendor/underscore"] - path = vendor/underscore - url = git://github.com/documentcloud/underscore.git -[submodule "vendor/backbone"] - path = vendor/backbone - url = git://github.com/documentcloud/backbone.git diff --git a/.npmignore b/.npmignore index 1c8397f333..02c82644f8 100644 --- a/.npmignore +++ b/.npmignore @@ -1,19 +1,17 @@ *.custom.* *.min.* .* -build.* -build/ dist/ doc/*.php node_modules/ perf/*.html perf/*.sh test/*.html +test/*-ui.js test/*.sh vendor/backbone/ -vendor/closure-compiler/ vendor/docdown/ -vendor/firebug-lite/ +vendor/qunit/qunit/*.css +vendor/underscore/ vendor/requirejs/ -vendor/uglifyjs/ -vendor/underscore/ \ No newline at end of file +vendor/firebug-lite/ diff --git a/README.md b/README.md index 1714f2ddcf..a322648490 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Lo-Dash v0.3.2 +# Lo-Dash v0.4.0 A drop-in replacement for Underscore.js, from the devs behind [jsPerf.com](http://jsperf.com), that delivers [performance improvements](http://lodash.com/benchmarks), [bug fixes](https://github.com/bestiejs/lodash#closed-underscorejs-issues), and [additional features](https://github.com/bestiejs/lodash#features). @@ -6,22 +6,26 @@ Lo-Dash’s performance is gained by avoiding slower native methods, instead opt ## Download - * [Development source](https://raw.github.com/bestiejs/lodash/v0.3.2/lodash.js) - * [Production source](https://raw.github.com/bestiejs/lodash/v0.3.2/lodash.min.js) + * [Development source](https://raw.github.com/bestiejs/lodash/v0.4.0/lodash.js) + * [Production source](https://raw.github.com/bestiejs/lodash/v0.4.0/lodash.min.js) + * CDN copies of ≤ [v0.3.2](http://cdnjs.cloudflare.com/ajax/libs/lodash.js/0.3.2/lodash.min.js) are available on [cdnjs](http://cdnjs.com/) thanks to [CloudFlare](http://www.cloudflare.com/) * For optimal performance, [create a custom build](https://github.com/bestiejs/lodash#custom-builds) with only the features you need ## Dive in We’ve got [API docs](http://lodash.com/docs), [benchmarks](http://lodash.com/benchmarks), and [unit tests](http://lodash.com/tests). +Create your own benchmarks at [jsPerf](http://jsperf.com), or [search](http://jsperf.com/search?q=lodash) for existing ones. + For a list of upcoming features, check out our [roadmap](https://github.com/bestiejs/lodash/wiki/Roadmap). ## Screencasts For more information check out these screencasts over Lo-Dash: - * [Introducing Lo-Dash](http://dl.dropbox.com/u/513327/allyoucanleet/post/20/file/screencast.mp4) - * [Optimizations and custom builds](http://dl.dropbox.com/u/513327/allyoucanleet/post/21/file/screencast.mp4) + * [Introducing Lo-Dash](https://vimeo.com/44154599) + * [Optimizations and custom builds](https://vimeo.com/44154601) + * [Lo-Dash’s origin and why it’s a better utility belt](https://vimeo.com/44154600) ## Features @@ -34,12 +38,13 @@ For more information check out these screencasts over Lo-Dash: * [_.groupBy](http://lodash.com/docs#groupBy), [_.sortedIndex](http://lodash.com/docs#sortedIndex), and [_.uniq](http://lodash.com/docs#uniq) accept a `thisArg` argument * [_.indexOf](http://lodash.com/docs#indexOf) and [_.lastIndexOf](http://lodash.com/docs#lastIndexOf) accept a `fromIndex` argument * [_.partial](http://lodash.com/docs#partial) for more functional fun - * [_.size](http://lodash.com/docs#size) supports returning the `length` of string values * [_.template](http://lodash.com/docs#template) 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 "_.every, _.filter, _.find, _.forEach, _.groupBy, _.invoke, _.map, _.pluck, _.reduce, _.reduceRight, _.reject, _.some, _sortBy") accept strings ## Support -Lo-Dash has been tested in at least Chrome 5-19, Firefox 1.5-13, IE 6-9, Opera 9.25-12, Safari 3.0.4-5.1.3, Node.js 0.4.8-0.6.18, Narwhal 0.3.2, RingoJS 0.8, and Rhino 1.7RC3. +Lo-Dash has been tested in at least Chrome 5-20, Firefox 1.5-13, IE 6-9, Opera 9.25-12, Safari 3.0.4-5.1.7, Node.js 0.4.8-0.8.2, Narwhal 0.3.2, RingoJS 0.8, and Rhino 1.7RC3. ## Custom builds @@ -48,12 +53,17 @@ We handle all the method dependency and alias mapping for you. * Backbone builds, containing all methods required by Backbone, may be created using the `backbone` modifier argument. ~~~ bash -node build backbone +lodash backbone +~~~ + + * Legacy builds, tailored for older browsers without [ES5 support](http://es5.github.com/), may be created using the `legacy` modifier argument. +~~~ bash +lodash legacy ~~~ * Mobile builds, with IE bug fixes and method compilation removed, may be created using the `mobile` modifier argument. ~~~ bash -node build mobile +lodash mobile ~~~ Custom builds may be created in three ways: @@ -61,29 +71,31 @@ Custom builds may be created in three ways: 1. Use the `category` argument to pass the categories of methods to include in the build.
Valid categories are *"arrays"*, *"chaining"*, *"collections"*, *"functions"*, *"objects"*, and *"utilities"*. ~~~ bash -node build category=collections,functions -node build category="collections, functions" +lodash category=collections,functions +lodash category="collections, functions" ~~~ 2. Use the `include` argument to pass the names of methods to include in the build. ~~~ bash -node build include=each,filter,map -node build include="each, filter, map" +lodash include=each,filter,map +lodash include="each, filter, map" ~~~ 3. Use the `exclude` argument to pass the names of methods to exclude from the build. ~~~ bash -node build exclude=union,uniq,zip -node build exclude="union, uniq, zip" +lodash exclude=union,uniq,zip +lodash exclude="union, uniq, zip" ~~~ -All arguments, except `include` and `exlcude`, may be combined. +All arguments, except `include` with `exclude` and `mobile` with `legacy`, may be combined. ~~~ bash -node build backbone mobile category=functions include=pick,uniq -node build backbone mobile category=utilities exclude=first,last +lodash backbone mobile category=functions include=pick,uniq +lodash backbone legacy category=utilities exclude=first,last ~~~ +The `lodash` command-line utility is available when Lo-Dash is installed as a global package (i.e. `npm install -g lodash`). + Custom builds are saved to `lodash.custom.js` and `lodash.custom.min.js`. ## Installation and usage @@ -98,6 +110,7 @@ Using [npm](http://npmjs.org/): ~~~ bash npm install lodash +npm install -g lodash ~~~ In [Node.js](http://nodejs.org/) and [RingoJS v0.8.0+](http://ringojs.org/): @@ -131,41 +144,31 @@ require({ }); ~~~ -## Cloning this repo - -To clone this repository including all submodules, using Git 1.6.5 or later: - -~~~ bash -git clone --recursive https://github.com/bestiejs/lodash.git -cd lodash.js -~~~ - -For older Git versions, just use: +## Closed Underscore.js issues (20+) -~~~ bash -git clone https://github.com/bestiejs/lodash.git -cd lodash -git submodule update --init -~~~ - -## Closed Underscore.js issues - - * Allow iteration of objects with a `length` property [[#148](https://github.com/documentcloud/underscore/issues/148), [#154](https://github.com/documentcloud/underscore/issues/154), [#252](https://github.com/documentcloud/underscore/issues/252), [#448](https://github.com/documentcloud/underscore/issues/448), [test](https://github.com/bestiejs/lodash/blob/1ba47a7c2a35552796f0c75dc2b46660e230f842/test/test.js#L271-276)] - * Ensure "Arrays" category methods allow falsey `array` arguments [[test](https://github.com/bestiejs/lodash/blob/1ba47a7c2a35552796f0c75dc2b46660e230f842/test/test.js#L758-790)] - * Ensure array-like objects with invalid `length` properties are treated like regular objects [[test](https://github.com/bestiejs/lodash/blob/1ba47a7c2a35552796f0c75dc2b46660e230f842/test/test.js#L242-248), [test](https://github.com/bestiejs/lodash/blob/1ba47a7c2a35552796f0c75dc2b46660e230f842/test/test.js#L560-569), [test](https://github.com/bestiejs/lodash/blob/1ba47a7c2a35552796f0c75dc2b46660e230f842/test/test.js#L705-708)] - * Ensure `_(…)` returns passed wrapper instances [[test](https://github.com/bestiejs/lodash/blob/801e8a5b3a963157fceaad15075690f59c22de9c/test/test.js#L106-109)] - * Ensure `_.escape` returns an empty string when passed `null` or `undefined` [[#407](https://github.com/documentcloud/underscore/issues/427), [test](https://github.com/bestiejs/lodash/blob/1ba47a7c2a35552796f0c75dc2b46660e230f842/test/test.js#L161-164)] - * Ensure `_.groupBy` adds values to own, not inherited, properties [[test](https://github.com/bestiejs/lodash/blob/1ba47a7c2a35552796f0c75dc2b46660e230f842/test/test.js#L322-329)] - * Ensure `_.sortedIndex` supports arrays with high `length` values [[test](https://github.com/bestiejs/lodash/blob/1ba47a7c2a35552796f0c75dc2b46660e230f842/test/test.js#L613-622)] - * Ensure `_.throttle` works when called in tight loops [[#502](https://github.com/documentcloud/underscore/issues/502), [test](https://github.com/bestiejs/lodash/blob/1ba47a7c2a35552796f0c75dc2b46660e230f842/test/test.js#L656-666)] - * Fix Firefox, IE, Opera, and Safari object iteration bugs [[#376](https://github.com/documentcloud/underscore/issues/376), [test](https://github.com/bestiejs/lodash/blob/1ba47a7c2a35552796f0c75dc2b46660e230f842/test/test.js#L180-192), [test](https://github.com/bestiejs/lodash/blob/1ba47a7c2a35552796f0c75dc2b46660e230f842/test/test.js#L282-307), [test](https://github.com/bestiejs/lodash/blob/1ba47a7c2a35552796f0c75dc2b46660e230f842/test/test.js#L395-406), [test](https://github.com/bestiejs/lodash/blob/1ba47a7c2a35552796f0c75dc2b46660e230f842/test/test.js#L414-416), [test](https://github.com/bestiejs/lodash/blob/1ba47a7c2a35552796f0c75dc2b46660e230f842/test/test.js#L434-454), [test](https://github.com/bestiejs/lodash/blob/1ba47a7c2a35552796f0c75dc2b46660e230f842/test/test.js#L581-583)] + * Allow iteration of objects with a `length` property [[#148](https://github.com/documentcloud/underscore/issues/148), [#154](https://github.com/documentcloud/underscore/issues/154), [#252](https://github.com/documentcloud/underscore/issues/252), [#448](https://github.com/documentcloud/underscore/issues/448), [#659](https://github.com/documentcloud/underscore/issues/659), [test](https://github.com/bestiejs/lodash/blob/v0.4.0/test/test.js#L306-312)] + * Ensure array-like objects with invalid `length` properties are treated like regular objects [[test](https://github.com/bestiejs/lodash/blob/v0.4.0/test/test.js#L257-263), [test](https://github.com/bestiejs/lodash/blob/v0.4.0/test/test.js#L607-621), [test](https://github.com/bestiejs/lodash/blob/v0.4.0/test/test.js#L840-843)] + * Ensure *"Arrays"* methods allow falsey `array` arguments [[test](https://github.com/bestiejs/lodash/blob/v0.4.0/test/test.js#L908-947)] + * Ensure *"Collections"* methods allow string `collection` arguments [[#247](https://github.com/documentcloud/underscore/issues/247), [#276](https://github.com/documentcloud/underscore/issues/276), [#561](https://github.com/documentcloud/underscore/pull/561), [test](https://github.com/bestiejs/lodash/blob/v0.4.0/test/test.js#L265-283), [test](https://github.com/bestiejs/lodash/blob/v0.4.0/test/test.js#L623-640), [test](https://github.com/bestiejs/lodash/blob/v0.4.0/test/test.js#L845-848)] + * Ensure templates compiled with errors are inspectable [[#666](https://github.com/documentcloud/underscore/issues/666), [test](https://github.com/bestiejs/lodash/blob/v0.4.0/test/test.js#L737-744)] + * Fix cross-browser object iteration bugs [[#376](https://github.com/documentcloud/underscore/issues/376), [test](https://github.com/bestiejs/lodash/blob/v0.4.0/test/test.js#L195-207), [test](https://github.com/bestiejs/lodash/blob/v0.4.0/test/test.js#L317-342), [test](https://github.com/bestiejs/lodash/blob/v0.4.0/test/test.js#L438-449), [test](https://github.com/bestiejs/lodash/blob/v0.4.0/test/test.js#L457-459), [test](https://github.com/bestiejs/lodash/blob/v0.4.0/test/test.js#L477-497), [test](https://github.com/bestiejs/lodash/blob/v0.4.0/test/test.js#L667-669)] * Handle arrays with `undefined` values correctly in IE < 9 [[#601](https://github.com/documentcloud/underscore/issues/601)] - * Methods should work on pages with incorrectly shimmed native methods [[#7](https://github.com/documentcloud/underscore/issues/7), [test](https://github.com/bestiejs/lodash/blob/1ba47a7c2a35552796f0c75dc2b46660e230f842/test/test.js#L88-94)] - * Register as AMD module, but still export to global [[#431](https://github.com/documentcloud/underscore/pull/431), [test](https://github.com/bestiejs/lodash/blob/1ba47a7c2a35552796f0c75dc2b46660e230f842/test/test.js#L72-86)] - * `_.forEach` should be chainable [[#142](https://github.com/documentcloud/underscore/issues/142), [test](https://github.com/bestiejs/lodash/blob/1ba47a7c2a35552796f0c75dc2b46660e230f842/test/test.js#L237-240)] - * `_isNaN(new Number(NaN))` should return `true` [[test](https://github.com/bestiejs/lodash/blob/1ba47a7c2a35552796f0c75dc2b46660e230f842/test/test.js#L424-426)] - * `_.reduceRight` should pass correct callback arguments when iterating objects [[test](https://github.com/bestiejs/lodash/blob/1ba47a7c2a35552796f0c75dc2b46660e230f842/test/test.js#L548-558)] - * `_.size` should return the `length` of string values [[test](https://github.com/bestiejs/lodash/blob/1ba47a7c2a35552796f0c75dc2b46660e230f842/test/test.js#L577-579)] + * Methods should work on pages with incorrectly shimmed native methods [[#7](https://github.com/documentcloud/underscore/issues/7), [test](https://github.com/bestiejs/lodash/blob/v0.4.0/test/test.js#L86-92)] + * Register as an AMD module, but still export to global [[#431](https://github.com/documentcloud/underscore/pull/431), [test](https://github.com/bestiejs/lodash/blob/v0.4.0/test/test.js#L70-84)] + * `_(…)` should return passed wrapper instances [[test](https://github.com/bestiejs/lodash/blob/v0.4.0/test/test.js#L104-107)] + * `_.contains` should work with strings [[#667](https://github.com/documentcloud/underscore/pull/667), [test](https://github.com/bestiejs/lodash/blob/v0.4.0/test/test.js#L138-147)] + * `_.escape` should return an empty string when passed `null` or `undefined` [[#407](https://github.com/documentcloud/underscore/issues/427), [test](https://github.com/bestiejs/lodash/blob/v0.4.0/test/test.js#L176-179)] + * `_.forEach` should be chainable [[#142](https://github.com/documentcloud/underscore/issues/142), [test](https://github.com/bestiejs/lodash/blob/v0.4.0/test/test.js#L252-255)] + * `_.groupBy` should add values to own, not inherited, properties [[test](https://github.com/bestiejs/lodash/blob/v0.4.0/test/test.js#L357-364)] + * `_isNaN(new Number(NaN))` should return `true` [[test](https://github.com/bestiejs/lodash/blob/v0.4.0/test/test.js#L467-469)] + * `_.reduceRight` should pass correct callback arguments when iterating objects [[test](https://github.com/bestiejs/lodash/blob/v0.4.0/test/test.js#L591-605)] + * `_.size` should return the `length` of string values [[test](https://github.com/bestiejs/lodash/blob/v0.4.0/test/test.js#L650-652)] + * `_.size` shouldn't error on falsey values [[#650](https://github.com/documentcloud/underscore/pull/650), [test](https://github.com/bestiejs/lodash/blob/v0.4.0/test/test.js#L654-661)] + * `_.size` should work with `arguments` objects cross-browser [[#653](https://github.com/documentcloud/underscore/issues/653), [test](https://github.com/bestiejs/lodash/blob/v0.4.0/test/test.js#L663-665)] + * `_.sortedIndex` should support arrays with high `length` values [[test](https://github.com/bestiejs/lodash/blob/v0.4.0/test/test.js#L707-716)] + * `_.template` should not augment the `options` object [[test](https://github.com/bestiejs/lodash/blob/v0.4.0/test/test.js#L731-735)] + * `_.throttle` should work when called in a tight loop [[#502](https://github.com/documentcloud/underscore/issues/502), [test](https://github.com/bestiejs/lodash/blob/v0.4.0/test/test.js#L791-801)] + * `_.zipObject` should accept less than two arguments [[test](https://github.com/bestiejs/lodash/blob/v0.4.0/test/test.js#L870-872)] ## Optimized methods (50+) @@ -190,10 +193,15 @@ git submodule update --init * `_.indexOf` * `_.intersection` * `_.invoke` + * `_.isArguments` + * `_.isDate` * `_.isEmpty` * `_.isEqual` * `_.isFinite` + * `_.isFunction` * `_.isObject` + * `_.isNumber` + * `_.isRegExp` * `_.isString` * `_.keys` * `_.lastIndexOf` @@ -225,14 +233,21 @@ git submodule update --init ## Release Notes -### v0.3.2 - - * Deprecated `_(…).chain`, `_.isFinite`, `_.isNaN`, `_.isNull`, `_.isUndefined`, `_.result`, and `_.size` - * Ensured `_.escape` returns an empty string when passed `null` or `undefined` - * Ensured `sourceURL` support doesn't cause errors in Adobe's JS engine. - * Fixed regression in generating custom builds - * Moved `_.invoke` and `_.pluck` back to the *"Collections"* category - * Moved `_.tap` to the *"Chaining"* category +### v0.4.0 + + * Added `bin` and `scripts` entries to package.json + * Added `legacy` build option + * Added cross-browser support for passing strings to *"Collections"* methods + * Added `_.zipObject` + * Leveraged `_.indexOf`'s `fromIndex` in `_.difference` and `_.without` + * Optimized compiled templates + * Optimized inlining the `iteratorTemplate` for builds + * Optimized object iteration for *"Collections"* methods + * Optimized partially applied `_.bind` in V8 + * Made compiled templates more debuggable + * Made `_.size` work with falsey values and consistent cross-browser with `arguments` objects + * Moved `_.groupBy` and `_.sortBy` back to the *"Collections"* category + * Removed `arguments` object from `_.range` The full changelog is available [here](https://github.com/bestiejs/lodash/wiki/Changelog). diff --git a/build.js b/build.js index 52cf7facbd..cbc829a24b 100755 --- a/build.js +++ b/build.js @@ -2,20 +2,46 @@ ;(function() { 'use strict'; - /** The Node filesystem and path modules */ + /** Load modules */ var fs = require('fs'), - path = require('path'); - - /** Load other modules */ - var lodash = require(path.join(__dirname, 'lodash')), + path = require('path'), + vm = require('vm'), minify = require(path.join(__dirname, 'build', 'minify')); + /** The current working directory */ + var cwd = process.cwd(); + + /** Flag used to specify a backbone build */ + var isBackbone = process.argv.indexOf('backbone') > -1; + + /** Flag used to specify a legacy build */ + var isLegacy = process.argv.indexOf('legacy') > -1; + + /** Flag used to specify a mobile build */ + var isMobile = !isLegacy && process.argv.indexOf('mobile') > -1; + /** Shortcut used to convert array-like objects to arrays */ var slice = [].slice; /** The lodash.js source */ var source = fs.readFileSync(path.join(__dirname, 'lodash.js'), 'utf8'); + /** Load customized Lo-Dash module */ + var lodash = (function() { + var sandbox = {}; + + if (isLegacy) { + ['isBindFast', 'isKeysFast', 'nativeBind', 'nativeIsArray', 'nativeKeys'].forEach(function(varName) { + source = replaceVar(source, varName, 'false'); + }); + } + else if (isMobile) { + source = replaceVar(source, 'isKeysFast', 'false'); + } + vm.runInNewContext(source, sandbox); + return sandbox._; + }()); + /** Used to associate aliases with their real names */ var aliasToRealMap = { 'all': 'every', @@ -181,9 +207,32 @@ 'values': [], 'without': ['indexOf'], 'wrap': [], - 'zip': ['max', 'pluck'] + 'zip': ['max', 'pluck'], + 'zipObject': [] }; + /** Used to `iteratorTemplate` */ + var iteratorOptions = [ + 'args', + 'array', + 'arrayBranch', + 'beforeLoop', + 'bottom', + 'exit', + 'firstArg', + 'hasDontEnumBug', + 'inLoop', + 'init', + 'isKeysFast', + 'iteratee', + 'object', + 'objectBranch', + 'noCharByIndex', + 'shadowed', + 'top', + 'useHas' + ]; + /** Collections of method names */ var excludeMethods, includeMethods, @@ -210,16 +259,10 @@ return pair[1]; }, ''); - /** Flag used to specify a backbone build */ - var isBackbone = process.argv.indexOf('backbone') > -1; - - /** Flag used to specify a mobile build */ - var isMobile = process.argv.indexOf('mobile') > -1; - /*--------------------------------------------------------------------------*/ /** - * Gets the aliases associated with a given `funcName`. + * Gets the aliases associated with a given function name. * * @private * @param {String} funcName The name of the function to get aliases for. @@ -230,7 +273,7 @@ } /** - * Gets an array of depenants for a function by the given `funcName`. + * Gets an array of depenants for a function by a given name. * * @private * @param {String} funcName The name of the function to query. @@ -271,7 +314,37 @@ } /** - * Gets the real name, not alias, of a given `funcName`. + * Gets the formatted source of the given function. + * + * @private + * @param {Function} func The function to process. + * @returns {String} Returns the formatted source. + */ + function getFunctionSource(func) { + var source = func.source || (func + ''); + + // all leading whitespace + return source.replace(/\n(?:.*)/g, function(match, index) { + match = match.slice(1); + return ( + match == '}' && source.indexOf('}', index + 2) == -1 ? '\n ' : '\n ' + ) + match; + }); + } + + /** + * Gets the `_.isArguments` fallback snippet from `source`. + * + * @private + * @param {String} source The source to inspect. + * @returns {String} Returns the `isArguments` fallback snippet. + */ + function getIsArgumentsFallback(source) { + return (source.match(/(?:\s*\/\/.*)*\s*if *\(!(?:lodash\.)?isArguments[^)]+\)[\s\S]+?};\s*}/) || [''])[0]; + } + + /** + * Gets the real name, not alias, of a given function name. * * @private * @param {String} funcName The name of the function to resolve. @@ -324,7 +397,7 @@ } /** - * Removes the all references to `refName` from the `createIterator` source. + * Removes the all references to `refName` from `createIterator` in `source`. * * @private * @param {String} source The source to process. @@ -380,7 +453,26 @@ * @returns {String} Returns the source with the `isArguments` fallback removed. */ function removeIsArgumentsFallback(source) { - return source.replace(/(?: *\/\/.*)*\s*if *\(!isArguments[^)]+\)[\s\S]+?};?\s*}\n/, ''); + return source.replace(getIsArgumentsFallback(source), ''); + } + + /** + * Removes the `Object.keys` object iteration optimization from `source`. + * + * @private + * @param {String} source The source to process. + * @returns {String} Returns the modified source. + */ + function removeKeysOptimization(source) { + return removeVar(source, 'isKeysFast') + // remove `isKeysFast` from `beforeLoop.object` of `mapIteratorOptions` + .replace(/=\s*'\s*\+\s*\(isKeysFast.+/, "= []'") + // remove `isKeysFast` from `inLoop.object` of `mapIteratorOptions`, `invoke`, `pluck`, and `sortBy` + .replace(/'\s*\+\s*\(isKeysFast[^)]+?\)\s*\+\s*'/g, '.push') + // remove data object property assignment in `createIterator` + .replace(/\s*.+?\.isKeysFast *=.+/, '') + // remove optimized branch in `iteratorTemplate` + .replace(/(?: *\/\/.*\n)*\s*'( *)<% *if *\(isKeysFast[\s\S]+?'\1<% *} *else *\{ *%>.+\n([\s\S]+?) *'\1<% *} *%>.+/, '$2'); } /** @@ -398,9 +490,9 @@ // match multi-line comment block '(?:\\n +/\\*[^*]*\\*+(?:[^/][^*]*\\*+)*/)?\\n' + // match a variable declaration that's not part of a declaration list - '( +)var ' + varName + ' *= *(?:.*?;|(?:Function\\(.+?|.*?[^,])\\n[\\s\\S]+?\\n\\1.+?;)\\n|' + + '( +)var ' + varName + ' *= *(?:.+?;|(?:Function\\(.+?|.*?[^,])\\n[\\s\\S]+?\\n\\1.+?;)\\n|' + // match a variable in a declaration list - '\\n +' + varName + ' *=.*?,' + + '\\n +' + varName + ' *=.+?,' + // end non-capturing group ')' ), ''); @@ -409,29 +501,41 @@ source = source.replace(RegExp('(var +)' + varName + ' *=.+?,\\s+'), '$1'); // remove a variable at the end of a variable declaration list - source = source.replace(RegExp(',\\s*' + varName + ' *=.*?;'), ';'); + source = source.replace(RegExp(',\\s*' + varName + ' *=.+?;'), ';'); return removeFromCreateIterator(source, varName); } /** - * Removes non-syntax critical whitespace from a string. + * Searches `source` for a `varName` variable declaration and replaces its + * assigned value with `varValue`. * * @private - * @param {String} source The source to process. - * @returns {String} Returns the source with whitespace removed. + * @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. */ - function removeWhitespace(source) { - return source.replace(/\[object |else if|function | in |return\s+[\w']|throw |typeof |var |@ |\\\\n|\\n|\s+/g, function(match) { - return match == false || match == '\\n' ? '' : match; - }); + function replaceVar(source, varName, varValue) { + // replace a variable that's not part of a declaration list + source = source.replace(RegExp( + '(( +)var ' + varName + ' *= *)' + + '(?:.+?;|(?:Function\\(.+?|.*?[^,])\\n[\\s\\S]+?\\n\\2.+?;)\\n' + ), '$1' + varValue + ';\n'); + + // replace a varaible at the start or middle of a declaration list + source = source.replace(RegExp('((?:var|\\n) +' + varName + ' *=).+?,'), '$1 ' + varValue + ','); + + // replace a variable at the end of a variable declaration list + source = source.replace(RegExp('(,\\s*' + varName + ' *=).+?;'), '$1 ' + varValue + ';'); + + return source; } /*--------------------------------------------------------------------------*/ // Backbone build if (isBackbone) { - // add any additional dependencies + // add any additional sub-dependencies backboneDependencies = getDependencies(backboneDependencies); if (filterType == 'exclude') { @@ -469,14 +573,13 @@ includeMethods = lodash.without.apply(lodash, [categoryMethods].concat(excludeMethods)); } else if (filterType) { - // merge backbone dependencies into `includeMethods` + // merge `categoryMethods` into `includeMethods` includeMethods = lodash.union(includeMethods, categoryMethods); } else { - // include only the Backbone dependencies + // include only the `categoryMethods` includeMethods = categoryMethods; } - filterType = 'include'; return true; }); @@ -509,7 +612,7 @@ }); } - // remove associated functions, variables and code snippets + // remove associated functions, variables, and code snippets if (isRemoved(source, 'isArguments')) { source = removeIsArgumentsFallback(source); } @@ -521,6 +624,9 @@ // remove `LoDash.prototype` additions source = source.replace(/(?:\s*\/\/.*)*\s*LoDash.prototype *=[\s\S]+?\/\*-+\*\//, ''); } + if (isRemoved(source, 'sortBy')) { + source = removeFunction(source, 'compareAscending'); + } if (isRemoved(source, 'template')) { // remove `templateSettings` assignment source = source.replace(/(?:\n +\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/)?\n *lodash\.templateSettings[\s\S]+?};\n/, ''); @@ -533,16 +639,16 @@ } if (isRemoved(source, 'bind')) { source = removeVar(source, 'nativeBind'); + source = removeVar(source, 'isBindFast'); } if (isRemoved(source, 'isArray')) { source = removeVar(source, 'nativeIsArray'); } if (isRemoved(source, 'keys')) { - source = removeVar(source, 'nativeKeys'); + source = removeFunction(source, 'shimKeys'); } if (isRemoved(source, 'clone', 'isObject', 'keys')) { source = removeVar(source, 'objectTypes'); - source = removeFromCreateIterator(source, 'objectTypes'); } if (isRemoved(source, 'bind', 'isArray', 'keys')) { source = removeVar(source, 'reNative'); @@ -559,8 +665,137 @@ /*--------------------------------------------------------------------------*/ + // simplify template snippets + source = source.replace( + RegExp( + "'else if \\(thisArg\\) \\{\\\\n' \\+\\s*" + + "' callback = iteratorBind\\(callback, thisArg\\)\\\\n' \\+\\s*" + + "'}'" + , 'g'), + "'else if (thisArg) callback = iteratorBind(callback, thisArg)'" + ); + + /*--------------------------------------------------------------------------*/ + + // DRY out isType functions + (function() { + var iteratorName = lodash.find(['forEach', 'forOwn'], function(funcName) { + return !isRemoved(source, funcName); + }); + + // skip this optimization if there are no iteration methods to use + if (!iteratorName) { + return; + } + var snippet, + funcNames = [], + objectSnippets = [], + token = '__isTypeToken__'; + + // build replacement code + lodash.forOwn({ + 'Arguments': "'[object Arguments]'", + 'Date': 'dateClass', + 'Function': 'funcClass', + 'Number': 'numberClass', + 'RegExp': 'regexpClass', + 'String': 'stringClass' + }, function(value, key) { + // skip `isArguments` if a legacy build + if (isLegacy && key == 'Arguments') { + return; + } + var funcName = 'is' + key, + funcCode = matchFunction(source, funcName); + + if (funcCode) { + if (!snippet) { + // use snippet to mark the insert position + snippet = funcCode; + } + funcNames.push(funcName); + objectSnippets.push("'" + key + "': " + value); + } + }); + + // skip this optimization if there are less than 2 isType functions + if (funcNames.length < 2) { + return; + } + // add a token to mark the position to insert new code + source = source.replace(snippet, '\n' + token + '\n' + snippet); + + // remove existing isType functions + funcNames.forEach(function(funcName) { + source = removeFunction(source, funcName); + }); + + // replace token with new DRY code + source = source.replace(token, + ' // add `_.' + funcNames.join('`, `_.') + '`\n' + + ' ' + iteratorName + '({\n ' + objectSnippets.join(',\n ') + '\n }, function(className, key) {\n' + + " lodash['is' + key] = function(value) {\n" + + ' return toString.call(value) == className;\n' + + ' };\n' + + ' });' + ); + + // tweak `isArguments` fallback + snippet = !isLegacy && getIsArgumentsFallback(source); + if (snippet) { + var modified = '\n' + snippet.replace(/isArguments/g, 'lodash.$&'); + source = source.replace(snippet, modified); + } + }()); + + /*--------------------------------------------------------------------------*/ + + if (isLegacy) { + ['isBindFast', 'nativeBind', 'nativeIsArray', 'nativeKeys'].forEach(function(varName) { + source = removeVar(source, varName); + }); + + ['bind', 'isArray'].forEach(function(funcName) { + var snippet = matchFunction(source, funcName), + modified = snippet; + + // remove native `Function#bind` branch in `_.bind` + if (funcName == 'bind' ) { + modified = modified.replace(/(?:\s*\/\/.*)*\s*else if *\(isBindFast[^}]+}/, ''); + } + // remove native `Array.isArray` branch in `_.isArray` + else if (funcName == 'isArray') { + modified = modified.replace(/nativeIsArray * \|\|/, ''); + } + source = source.replace(snippet, modified); + }); + + // replace `_.keys` with `shimKeys` + if (!isRemoved(source, 'keys')) { + source = source.replace( + matchFunction(source, 'keys').replace(/[\s\S]+?var keys *=/, ''), + matchFunction(source, 'shimKeys').replace(/[\s\S]+?var shimKeys *=/, '') + ); + + source = removeFunction(source, 'shimKeys'); + } + // replace `_.isArguments` with fallback + if (!isRemoved(source, 'isArguments')) { + source = source.replace( + matchFunction(source, 'isArguments').replace(/[\s\S]+?var isArguments *=/, ''), + getIsArgumentsFallback(source).match(/isArguments *=([\s\S]+?) *};/)[1] + ' };\n' + ); + + source = removeIsArgumentsFallback(source); + } + + source = removeVar(source, 'reNative'); + source = removeFromCreateIterator(source, 'nativeKeys'); + source = removeKeysOptimization(source); + } + if (isMobile) { - // inline functions defined with `createIterator` + // inline all functions defined with `createIterator` lodash.functions(lodash).forEach(function(funcName) { // match `funcName` with pseudo private `_` prefixes removed to allow matching `shimKeys` var reFunc = RegExp('(\\bvar ' + funcName.replace(/^_/, '') + ' *= *)createIterator\\(((?:{|[a-zA-Z])[\\s\\S]+?)\\);\\n'); @@ -569,42 +804,68 @@ if (!reFunc.test(source)) { return; } - // extract and format the function's code - var code = (lodash[funcName] + '').replace(/\n(?:.*)/g, function(match) { - match = match.slice(1); - return (match == '}' ? '\n ' : '\n ') + match; - }); - - source = source.replace(reFunc, '$1' + code + ';\n'); + // extract, format, and inject the compiled function's source code + source = source.replace(reFunc, '$1' + getFunctionSource(lodash[funcName]) + ';\n'); }); - source = removeIsArgumentsFallback(source); + // remove JScript [[DontEnum]] fix from `_.isEqual` + source = source.replace(/(?:\s*\/\/.*)*\n( +)if *\(result *&& *hasDontEnumBug[\s\S]+?\n\1}/, ''); - source = removeVar(source, 'iteratorTemplate'); + // remove IE `shift` and `splice` fix from mutator Array functions mixin + source = source.replace(/(?:\s*\/\/.*)*\n( +)if *\(value.length *=== *0[\s\S]+?\n\1}/, ''); - // remove JScript [[DontEnum]] fix from `isEqual` - source = source.replace(/(?:\s*\/\/.*\n)*( +)if *\(result *&& *hasDontEnumBug[\s\S]+?\n\1}/, ''); + // remove `noCharByIndex` from `_.reduceRight` + source = source.replace(/noCharByIndex *&&[^:]+: *([^;]+)/g, '$1'); - // remove IE `shift` and `splice` fix - source = source.replace(/(?:\s*\/\/.*\n)*( +)if *\(value.length *=== *0[\s\S]+?\n\1}/, ''); + // remove `noArraySliceOnStrings` from `_.toArray` + source = source.replace(/noArraySliceOnStrings *\?[^:]+: *([^)]+)/g, '$1'); + + source = removeVar(source, 'extendIteratorOptions'); + source = removeVar(source, 'hasDontEnumBug'); + source = removeVar(source, 'iteratorTemplate'); + source = removeVar(source, 'noArraySliceOnStrings'); + source = removeVar(source, 'noCharByIndex'); + source = removeIsArgumentsFallback(source); + source = removeKeysOptimization(source); } else { // inline `iteratorTemplate` template - source = source.replace(/(( +)var iteratorTemplate *= *)([\s\S]+?\n\2.+?);\n/, (function() { - // extract `iteratorTemplate` code - var code = /^function[^{]+{([\s\S]+?)}$/.exec(lodash._iteratorTemplate)[1]; - - code = removeWhitespace(code) - // remove unnecessary code - .replace(/\|\|\{\}|,__t,__j=Array.prototype.join|function print[^}]+}|\+''/g, '') - .replace(/(\{);|;(\})/g, '$1$2') - .replace(/\(\(__t=\(([^)]+)\)\)==null\?'':__t\)/g, '$1') - // ensure escaped characters are interpreted correctly in the string literal - .replace(/\\/g, '\\\\'); - - // add `code` to `Function()` as a string literal to avoid strict mode - // errors caused by the required with-statement - return '$1Function(\'obj\',\n$2 "' + code + '"\n$2);\n'; + source = source.replace(/(( +)var iteratorTemplate *= *)[\s\S]+?\n\2.+?;\n/, (function() { + var snippet = getFunctionSource(lodash._iteratorTemplate); + + // prepend data object references to property names to avoid having to + // use a with-statement + iteratorOptions.forEach(function(property) { + if (property == 'iteratee') { + // use a more fine-grained regexp for the `iteratee` property because + // it's a compiled variable as well as a data property + snippet = snippet.replace(/(__t *= *\( *)(iteratee)/, '$1obj.$2'); + } else { + snippet = snippet.replace(RegExp('([^\\w.])\\b' + property + '\\b', 'g'), '$1obj.' + property); + } + }); + + // remove unnecessary code + snippet = snippet + .replace(/, *__t,[^;]+|function print[^}]+}/g, '') + .replace(/'(?:\\n|\s)+'/g, "''") + .replace(/__p *\+= *' *';/g, '') + .replace(/(__p *\+= *)' *' *\+/g, '$1') + .replace(/(\{) *;|; *(\})/g, '$1$2') + .replace(/\(\(__w?t *= *\( *([^)]+) *\)\) *== *null *\? *'' *: *__w?t\)/g, '$1'); + + // remove the with-statement + snippet = snippet.replace(/ *with *\(.+?\) *{/, '\n').replace(/}([^}]*}[^}]*$)/, '$1'); + + // minor cleanup + snippet = snippet + .replace(/obj *\|\| *\(obj *= *\{}\);/, '') + .replace(/var __p;\s*__p/, 'var __p'); + + // remove comments, including sourceURLs + snippet = snippet.replace(/\s*\/\/.*(?:\n|$)/g, ''); + + return '$1' + snippet + ';\n'; }())); } @@ -613,16 +874,19 @@ // remove pseudo private properties source = source.replace(/(?:(?:\s*\/\/.*)*\s*lodash\._[^=]+=.+\n)+/g, '\n'); + // cleanup code + source = source.replace(/^ *;\n/gm, ''); + // begin the minification process - if (filterType || isBackbone || isMobile) { - fs.writeFileSync(path.join(__dirname, 'lodash.custom.js'), source); + if (filterType || isBackbone || isLegacy || isMobile) { + fs.writeFileSync(path.join(cwd, 'lodash.custom.js'), source); minify(source, 'lodash.custom.min', function(result) { - fs.writeFileSync(path.join(__dirname, 'lodash.custom.min.js'), result); + fs.writeFileSync(path.join(cwd, 'lodash.custom.min.js'), result); }); } else { minify(source, 'lodash.min', function(result) { - fs.writeFileSync(path.join(__dirname, 'lodash.min.js'), result); + fs.writeFileSync(path.join(cwd, 'lodash.min.js'), result); }); } }()); diff --git a/build/minify.js b/build/minify.js index 39efec5e09..29e355d33a 100755 --- a/build/minify.js +++ b/build/minify.js @@ -35,8 +35,8 @@ /*--------------------------------------------------------------------------*/ /** - * The exposed `minify` function minifies a given `source` and invokes the - * `onComplete` callback when finished. + * The exposed `minify` function minifies a given Lo-Dash `source` and invokes + * the `onComplete` callback when finished. * * @param {String} source The source to minify. * @param {String} workingName The name to give temporary files creates during the minification process. @@ -58,7 +58,10 @@ function Minify(source, workingName, onComplete) { // create the destination directory if it doesn't exist if (!fs.existsSync(distPath)) { - fs.mkdirSync(distPath); + // avoid errors when called as a npm executable + try { + fs.mkdirSync(distPath); + } catch(e) { } } this.compiled = {}; @@ -291,17 +294,20 @@ name = this.workingName, uglified = this.uglified; - // save the Closure Compiled version to disk - fs.writeFileSync(path.join(distPath, name + '.compiler.js'), compiled.source); - fs.writeFileSync(path.join(distPath, name + '.compiler.js.gz'), compiled.gzip); + // avoid errors when called as a npm executable + try { + // save the Closure Compiled version to disk + fs.writeFileSync(path.join(distPath, name + '.compiler.js'), compiled.source); + fs.writeFileSync(path.join(distPath, name + '.compiler.js.gz'), compiled.gzip); - // save the Uglified version to disk - fs.writeFileSync(path.join(distPath, name + '.uglify.js'), uglified.source); - fs.writeFileSync(path.join(distPath, name + '.uglify.js.gz'), uglified.gzip); + // save the Uglified version to disk + fs.writeFileSync(path.join(distPath, name + '.uglify.js'), uglified.source); + fs.writeFileSync(path.join(distPath, name + '.uglify.js.gz'), uglified.gzip); - // save the hybrid minified version to disk - fs.writeFileSync(path.join(distPath, name + '.hybrid.js'), hybrid.source); - fs.writeFileSync(path.join(distPath, name + '.hybrid.js.gz'), hybrid.gzip); + // save the hybrid minified version to disk + fs.writeFileSync(path.join(distPath, name + '.hybrid.js'), hybrid.source); + fs.writeFileSync(path.join(distPath, name + '.hybrid.js.gz'), hybrid.gzip); + } catch(e) { } // select the smallest gzipped file and use its minified counterpart as the // official minified release (ties go to Closure Compiler) @@ -324,9 +330,9 @@ module.exports = minify; } else { - // read the JavaScript source file from the first argument if the script + // read the Lo-Dash source file from the first argument if the script // was invoked directly (e.g. `node minify.js source.js`) and write to - // the same file + // `.min.js` (function() { var filePath = process.argv[2], dirPath = path.dirname(filePath), @@ -334,7 +340,7 @@ workingName = path.basename(filePath, '.js') + '.min'; minify(source, workingName, function(result) { - fs.writeFileSync(path.join(dirPath, workingName + '.js'), result); + fs.writeFileSync(path.join(dirPath, workingName + '.js'), result, 'utf8'); }); }()); } diff --git a/build/post-compile.js b/build/post-compile.js index c93a0773ff..915d39f7da 100644 --- a/build/post-compile.js +++ b/build/post-compile.js @@ -15,7 +15,7 @@ /*--------------------------------------------------------------------------*/ /** - * Post-process a given minified JavaScript `source`, preparing it for + * Post-process a given minified Lo-Dash `source`, preparing it for * deployment. * * @param {String} source The source to process. @@ -56,7 +56,7 @@ if (module != require.main) { module.exports = postprocess; } else { - // read the JavaScript source file from the first argument if the script + // read the Lo-Dash source file from the first argument if the script // was invoked directly (e.g. `node post-compile.js source.js`) and write to // the same file (function() { diff --git a/build/pre-compile.js b/build/pre-compile.js index 7f0a305020..5736212e7c 100644 --- a/build/pre-compile.js +++ b/build/pre-compile.js @@ -13,20 +13,26 @@ 'callback', 'className', 'collection', + 'compareAscending', 'ctor', - 'false', 'funcClass', 'hasOwnProperty', 'identity', 'index', 'isFunc', + 'iteratee', 'iteratorBind', 'length', 'methodName', + 'nativeKeys', 'noaccum', 'object', 'objectTypes', + 'prop', + 'propIndex', + 'props', 'property', + 'propertyIsEnumerable', 'result', 'skipProto', 'slice', @@ -36,8 +42,6 @@ 'target', 'thisArg', 'toString', - 'true', - 'undefined', 'value' ]; @@ -50,14 +54,14 @@ 'bottom', 'exit', 'firstArg', - 'hasExp', 'hasDontEnumBug', 'inLoop', 'init', - 'iteratedObject', - 'loopExp', + 'isKeysFast', + 'iteratee', 'object', 'objectBranch', + 'noCharByIndex', 'shadowed', 'top', 'useHas' @@ -75,6 +79,7 @@ 'all', 'amd', 'any', + 'attachEvent', 'bind', 'bindAll', 'chain', @@ -184,13 +189,14 @@ 'VERSION', 'without', 'wrap', - 'zip' + 'zip', + 'zipObject' ]; /*--------------------------------------------------------------------------*/ /** - * Pre-process a given JavaScript `source`, preparing it for minification. + * Pre-process a given Lo-Dash `source`, preparing it for minification. * * @param {String} source The source to process. * @returns {String} Returns the processed source. @@ -207,7 +213,16 @@ source = source.replace(RegExp('\\.(' + propWhitelist.join('|') + ')\\b', 'g'), "['$1']"); // remove brackets from `_.escape()` in `tokenizeEscape` - source = source.replace("_['escape'](\"", '_.escape("'); + source = source.replace(/_\['escape']\("/, '_.escape("'); + + // remove brackets from `_.escape()` in `_.template` + source = source.replace(/__e *= *_\['escape']/, '__e=_.escape'); + + // remove brackets from `collection.indexOf` in `_.contains` + source = source.replace("collection['indexOf'](target)", 'collection.indexOf(target)'); + + // remove brackets from `result[length].value` in `_.sortBy` + source = source.replace("result[length]['value']", 'result[length].value'); // remove whitespace from string literals source = source.replace(/'(?:(?=(\\?))\1.)*?'/g, function(string) { @@ -217,8 +232,18 @@ }); }); - // remove newline from double-quoted string in `_.template` - source = source.replace('"\';\\n"', '"\';"'); + // remove whitespace from `_.template` related regexpes + source = source.replace(/(?:reDelimiterCode\w+|reEmptyString\w+|reInsertVariable) *=.+/g, function(match) { + return match.replace(/ |\\n/g, ''); + }); + + // 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'", "'){'") // remove `useSourceURL` variable source = source.replace(/(?:\n +\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/)?\n *try *\{(?:\s*\/\/.*\n)* *var useSourceURL[\s\S]+?catch[^}]+}\n/, ''); @@ -226,33 +251,46 @@ // remove debug sourceURL use in `_.template` source = source.replace(/(?:\s*\/\/.*\n)* *if *\(useSourceURL[^}]+}/, ''); - // minify `_.sortBy` internal properties + // minify internal properties used by `_.sortBy` (function() { var properties = ['criteria', 'value'], - snippet = (source.match(/( +)function sortBy\b[\s\S]+?\n\1}/) || 0)[0], - result = snippet; + snippets = source.match(/( +)(?:function compareAscending|var sortBy)\b[\s\S]+?\n\1}/g); + + if (!snippets) { + return; + } + snippets.forEach(function(snippet) { + var modified = snippet, + isSortBy = /var sortBy\b/.test(modified), + isInlined = !/\bcreateIterator\b/.test(modified); - if (snippet) { // minify properties properties.forEach(function(property, index) { - result = result.replace(RegExp('\\b' + property + '\\b', 'g'), minNames[index]); + // add quotes around properties in the inlined `_.sortBy` of the mobile + // build so Closure Compiler won't mung them + if (isSortBy && isInlined) { + modified = modified + .replace(RegExp('\\.' + property + '\\b', 'g'), "['" + minNames[index] + "']") + .replace(RegExp('\\b' + property + ' *:', 'g'), "'" + minNames[index] + "':"); + } + modified = modified.replace(RegExp('\\b' + property + '\\b', 'g'), minNames[index]); }); // replace with modified snippet - source = source.replace(snippet, result); - } + source = source.replace(snippet, modified); + }); }()); // minify all compilable snippets var snippets = source.match( RegExp([ // match the `iteratorTemplate` - 'var iteratorTemplate\\b[\\s\\S]+?\\);\\n', + '( +)var iteratorTemplate\\b[\\s\\S]+?\\n\\1}', // match methods created by `createIterator` calls 'createIterator\\((?:{|[a-zA-Z]+)[\\s\\S]+?\\);\\n', // match variables storing `createIterator` options - '( +)var [a-zA-Z]+IteratorOptions\\b[\\s\\S]+?\\n\\1}', + '( +)var [a-zA-Z]+IteratorOptions\\b[\\s\\S]+?\\n\\2}', // match the the `createIterator` function - '( +)function createIterator\\b[\\s\\S]+?\\n\\2}' + '( +)function createIterator\\b[\\s\\S]+?\\n\\3}' ].join('|'), 'g') ); @@ -264,38 +302,26 @@ snippets.forEach(function(snippet, index) { var isCreateIterator = /function createIterator\b/.test(snippet), isIteratorTemplate = /var iteratorTemplate\b/.test(snippet), - result = snippet; - + modified = snippet; // add brackets to whitelisted properties so Closure Compiler won't mung them - result = result.replace(RegExp('\\.(' + iteratorOptions.join('|') + ')\\b', 'g'), "['$1']"); + modified = modified.replace(RegExp('\\.(' + iteratorOptions.join('|') + ')\\b', 'g'), "['$1']"); if (isCreateIterator) { - // add `true` and `false` arguments to be minified - result = result - .replace(/(Function\(\s*'[\s\S]+?)undefined/, '$1true,false,undefined') - .replace(/factory\([^)]+/, '$&,true,false'); - // replace with modified snippet early and clip snippet so other arguments // aren't minified - source = source.replace(snippet, result); - snippet = result = result.replace(/factory\([\s\S]+$/, ''); + source = source.replace(snippet, modified); + snippet = modified = modified.replace(/factory\([\s\S]+$/, ''); } // minify snippet variables / arguments compiledVars.forEach(function(variable, index) { // ensure properties in compiled strings aren't minified - result = result.replace(RegExp('([^.]\\b)' + variable + '\\b(?!\' *[\\]:])', 'g'), '$1' + minNames[index]); + modified = modified.replace(RegExp('([^.]\\b)' + variable + '\\b(?!\' *[\\]:])', 'g'), '$1' + minNames[index]); // correct `typeof x == 'object'` if (variable == 'object') { - result = result.replace(RegExp("(typeof [^']+')" + minNames[index] + "'", 'g'), "$1object'"); - } - // correct external boolean literals - else if (variable == 'true' || variable == 'false') { - result = result - .replace(RegExp(': *' + minNames[index] + '([,\\n])', 'g'), ':' + variable + '$1') - .replace(RegExp('\\b' + minNames[index] + ';', 'g'), variable + ';'); + modified = modified.replace(RegExp("(typeof [^']+')" + minNames[index] + "'", 'g'), "$1object'"); } }); @@ -303,26 +329,26 @@ iteratorOptions.forEach(function(property, index) { if (isIteratorTemplate) { // minify property names as interpolated template variables - result = result.replace(RegExp('\\b' + property + '\\b', 'g'), minNames[index]); + modified = modified.replace(RegExp('\\b' + property + '\\b', 'g'), minNames[index]); } else { if (property == 'array' || property == 'object') { // minify "array" and "object" sub property names - result = result.replace(RegExp("'" + property + "'( *[\\]:])", 'g'), "'" + minNames[index] + "'$1"); + modified = modified.replace(RegExp("'" + property + "'( *[\\]:])", 'g'), "'" + minNames[index] + "'$1"); } else { // minify property name strings - result = result.replace(RegExp("'" + property + "'", 'g'), "'" + minNames[index] + "'"); + modified = modified.replace(RegExp("'" + property + "'", 'g'), "'" + minNames[index] + "'"); // minify property names in regexps and accessors if (isCreateIterator) { - result = result.replace(RegExp('([\\.|/])' + property + '\\b' , 'g'), '$1' + minNames[index]); + modified = modified.replace(RegExp('([\\.|/])' + property + '\\b' , 'g'), '$1' + minNames[index]); } } } }); // replace with modified snippet - source = source.replace(snippet, result); + source = source.replace(snippet, modified); }); return source; @@ -335,7 +361,7 @@ module.exports = preprocess; } else { - // read the JavaScript source file from the first argument if the script + // read the Lo-Dash source file from the first argument if the script // was invoked directly (e.g. `node pre-compile.js source.js`) and write to // the same file (function() { diff --git a/doc/README.md b/doc/README.md index ceab12c141..19557f49c4 100644 --- a/doc/README.md +++ b/doc/README.md @@ -1,4 +1,4 @@ -# Lo-Dash v0.3.2 +# Lo-Dash v0.4.0 @@ -32,7 +32,7 @@ * [`_.forIn`](#_forinobject-callback--thisarg) * [`_.forOwn`](#_forownobject-callback--thisarg) * [`_.functions`](#_functionsobject) -* [`_.groupBy`](#_groupbyarray-callback--thisarg) +* [`_.groupBy`](#_groupbycollection-callback--thisarg) * [`_.has`](#_hasobject-property) * [`_.identity`](#_identityvalue) * [`_.indexOf`](#_indexofarray-value--fromindex0) @@ -77,7 +77,7 @@ * [`_.shuffle`](#_shufflearray) * [`_.size`](#_sizevalue) * [`_.some`](#_somecollection--callbackidentity-thisarg) -* [`_.sortBy`](#_sortbyarray-callback--thisarg) +* [`_.sortBy`](#_sortbycollection-callback--thisarg) * [`_.sortedIndex`](#_sortedindexarray-value--callbackidentity-thisarg) * [`_.tap`](#_tapvalue-interceptor) * [`_.template`](#_templatetext-data-options) @@ -91,6 +91,7 @@ * [`_.without`](#_withoutarray--value1-value2-) * [`_.wrap`](#_wrapfunc-wrapper--arg1-arg2-) * [`_.zip`](#_ziparray1-array2-) +* [`_.zipObject`](#_zipobjectkeys) @@ -129,7 +130,7 @@ ### `_(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L140 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L197 "View in source") [Ⓣ][1] The `lodash` function. @@ -147,7 +148,7 @@ The `lodash` function. ### `_.VERSION` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L3366 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3593 "View in source") [Ⓣ][1] *(String)*: The semantic version number. @@ -159,7 +160,7 @@ The `lodash` function. ### `_.after(n, func)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L1797 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1953 "View in source") [Ⓣ][1] Creates a new function that is restricted to executing only after it is called `n` times. @@ -187,7 +188,7 @@ _.forEach(notes, function(note) { ### `_.bind(func [, thisArg, arg1, arg2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L1851 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2007 "View in source") [Ⓣ][1] Creates a new 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. Lazy defined methods may be bound by passing the object they are bound to as `func` and the method name as `thisArg`. @@ -203,24 +204,24 @@ Creates a new function that, when called, invokes `func` with the `this` binding ~~~ js // basic bind var func = function(greeting) { - return greeting + ': ' + this.name; + return greeting + ' ' + this.name; }; func = _.bind(func, { 'name': 'moe' }, 'hi'); func(); -// => 'hi: moe' +// => 'hi moe' // lazy bind var object = { 'name': 'moe', 'greet': function(greeting) { - return greeting + ': ' + this.name; + return greeting + ' ' + this.name; } }; var func = _.bind(object, 'greet', 'hi'); func(); -// => 'hi: moe' +// => 'hi moe' object.greet = function(greeting) { return greeting + ', ' + this.name + '!'; @@ -238,7 +239,7 @@ func(); ### `_.bindAll(object [, methodName1, methodName2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L1922 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2077 "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. @@ -253,8 +254,7 @@ Binds methods on `object` to `object`, overwriting the existing method. If no me ~~~ js var buttonView = { 'label': 'lodash', - 'onClick': function() { alert('clicked: ' + this.label); }, - 'onHover': function() { console.log('hovering: ' + this.label); } + 'onClick': function() { alert('clicked: ' + this.label); } }; _.bindAll(buttonView); @@ -270,7 +270,7 @@ jQuery('#lodash_button').on('click', buttonView.onClick); ### `_.chain(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L3291 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3518 "View in source") [Ⓣ][1] Wraps the value in a `lodash` wrapper object. @@ -304,7 +304,7 @@ var youngest = _.chain(stooges) ### `_.clone(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2248 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2403 "View in source") [Ⓣ][1] Create a shallow clone of the `value`. Any nested objects or arrays will be assigned by reference and not cloned. @@ -328,7 +328,7 @@ _.clone({ 'name': 'moe' }); ### `_.compact(array)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L963 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1200 "View in source") [Ⓣ][1] Produces a new array with all falsey values of `array` removed. The values `false`, `null`, `0`, `""`, `undefined` and `NaN` are all falsey. @@ -352,7 +352,7 @@ _.compact([0, 1, false, 2, '', 3]); ### `_.compose([func1, func2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L1954 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2109 "View in source") [Ⓣ][1] Creates a new 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()))`. @@ -379,12 +379,12 @@ welcome('moe'); ### `_.contains(collection, target)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L598 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L726 "View in source") [Ⓣ][1] Checks if a given `target` value is present in a `collection` using strict equality for comparisons, i.e. `===`. #### Arguments -1. `collection` *(Array|Object)*: The collection to iterate over. +1. `collection` *(Array|Object|String)*: The collection to iterate over. 2. `target` *(Mixed)*: The value to check for. #### Returns @@ -394,6 +394,12 @@ Checks if a given `target` value is present in a `collection` using strict equal ~~~ js _.contains([1, 2, 3], 3); // => true + +_.contains({ 'name': 'moe', 'age': 40 }, 'moe'); +// => true + +_.contains('curly', 'ur'); +// => true ~~~ * * * @@ -404,7 +410,7 @@ _.contains([1, 2, 3], 3); ### `_.debounce(func, wait, immediate)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L1987 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2142 "View in source") [Ⓣ][1] Creates a new 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. @@ -430,7 +436,7 @@ jQuery(window).on('resize', lazyLayout); ### `_.defaults(object [, defaults1, defaults2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2271 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2426 "View in source") [Ⓣ][1] Assigns missing properties on `object` with default values from the defaults objects. Once a property is set, additional defaults of the same property will be ignored. @@ -456,7 +462,7 @@ _.defaults(iceCream, { 'flavor': 'vanilla', 'sprinkles': 'rainbow' }); ### `_.defer(func [, arg1, arg2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2052 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2207 "View in source") [Ⓣ][1] Defers executing the `func` function until the current call stack has cleared. Additional arguments are passed to `func` when it is invoked. @@ -481,7 +487,7 @@ _.defer(function() { alert('deferred'); }); ### `_.delay(func, wait [, arg1, arg2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2032 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2187 "View in source") [Ⓣ][1] Executes the `func` function after `wait` milliseconds. Additional arguments are passed to `func` when it is invoked. @@ -508,7 +514,7 @@ _.delay(log, 1000, 'logged later'); ### `_.difference(array [, array1, array2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L995 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1232 "View in source") [Ⓣ][1] Produces a new array of `array` values not present in the other arrays using strict equality for comparisons, i.e. `===`. @@ -533,7 +539,7 @@ _.difference([1, 2, 3, 4, 5], [5, 2, 10]); ### `_.escape(string)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2976 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3135 "View in source") [Ⓣ][1] Escapes a string for inclusion in HTML, replacing `&`, `<`, `"`, and `'` characters. @@ -557,12 +563,12 @@ _.escape('Curly, Larry & Moe'); ### `_.every(collection [, callback=identity, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L623 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L755 "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 `3` arguments; for arrays they are *(value, index, array)* and for objects they are *(value, key, object)*. #### Arguments -1. `collection` *(Array|Object)*: The collection to iterate over. +1. `collection` *(Array|Object|String)*: The collection to iterate over. 2. `[callback=identity]` *(Function)*: The function called per iteration. 3. `[thisArg]` *(Mixed)*: The `this` binding for the callback. @@ -583,7 +589,7 @@ _.every([true, 1, null, 'yes'], Boolean); ### `_.extend(object [, source1, source2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2290 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2445 "View in source") [Ⓣ][1] Copies enumerable properties from the source objects to the `destination` object. Subsequent sources will overwrite propery assignments of previous sources. @@ -608,12 +614,12 @@ _.extend({ 'name': 'moe' }, { 'age': 40 }); ### `_.filter(collection [, callback=identity, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L644 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L776 "View in source") [Ⓣ][1] Examines each value in a `collection`, returning an array of all values the `callback` returns truthy for. The `callback` is bound to `thisArg` and invoked with `3` arguments; for arrays they are *(value, index, array)* and for objects they are *(value, key, object)*. #### Arguments -1. `collection` *(Array|Object)*: The collection to iterate over. +1. `collection` *(Array|Object|String)*: The collection to iterate over. 2. `[callback=identity]` *(Function)*: The function called per iteration. 3. `[thisArg]` *(Mixed)*: The `this` binding for the callback. @@ -634,12 +640,12 @@ 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/v0.3.2/lodash.js#L666 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L798 "View in source") [Ⓣ][1] Examines each value in a `collection`, returning the first one the `callback` returns truthy for. The function returns as soon as it finds an acceptable value, and does not iterate over the entire `collection`. The `callback` is bound to `thisArg` and invoked with `3` arguments; for arrays they are *(value, index, array)* and for objects they are *(value, key, object)*. #### Arguments -1. `collection` *(Array|Object)*: The collection to iterate over. +1. `collection` *(Array|Object|String)*: The collection to iterate over. 2. `callback` *(Function)*: The function called per iteration. 3. `[thisArg]` *(Mixed)*: The `this` binding for the callback. @@ -660,7 +666,7 @@ var even = _.find([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); ### `_.first(array [, n, guard])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L1031 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1268 "View in source") [Ⓣ][1] Gets the first value of the `array`. Pass `n` to return the first `n` values of the `array`. @@ -686,7 +692,7 @@ _.first([5, 4, 3, 2, 1]); ### `_.flatten(array, shallow)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L1055 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1292 "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. @@ -714,12 +720,12 @@ _.flatten([1, [2], [3, [[4]]]], true); ### `_.forEach(collection, callback [, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L693 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L825 "View in source") [Ⓣ][1] Iterates over a `collection`, executing the `callback` for each value in the `collection`. The `callback` is bound to `thisArg` and invoked with `3` arguments; for arrays they are *(value, index, array)* and for objects they are *(value, key, object)*. #### Arguments -1. `collection` *(Array|Object)*: The collection to iterate over. +1. `collection` *(Array|Object|String)*: The collection to iterate over. 2. `callback` *(Function)*: The function called per iteration. 3. `[thisArg]` *(Mixed)*: The `this` binding for the callback. @@ -743,7 +749,7 @@ _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, alert); ### `_.forIn(object, callback [, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2319 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2474 "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 `3` arguments; *(value, key, object)*. @@ -779,7 +785,7 @@ _.forIn(new Dog('Dagny'), function(value, key) { ### `_.forOwn(object, callback [, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2342 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2497 "View in source") [Ⓣ][1] Iterates over `object`'s own enumerable properties, executing the `callback` for each property. The `callback` is bound to `thisArg` and invoked with `3` arguments; *(value, key, object)*. @@ -807,7 +813,7 @@ _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { ### `_.functions(object)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2359 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2514 "View in source") [Ⓣ][1] Produces a sorted array of the enumerable properties, own and inherited, of `object` that have function values. @@ -830,13 +836,13 @@ _.functions(_); -### `_.groupBy(array, callback [, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L1100 "View in source") [Ⓣ][1] +### `_.groupBy(collection, callback [, thisArg])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L853 "View in source") [Ⓣ][1] -Splits `array` into sets, grouped by the result of running each value through `callback`. The `callback` is bound to `thisArg` and invoked with `3` arguments; *(value, index, array)*. The `callback` argument may also be the name of a property to group by. +Splits `collection` into sets, grouped by the result of running each value through `callback`. The `callback` is bound to `thisArg` and invoked with `3` arguments; for arrays they are *(value, index, array)* and for objects they are *(value, key, object)*. The `callback` argument may also be the name of a property to group by. #### Arguments -1. `array` *(Array)*: The array to iterate over. +1. `collection` *(Array|Object|String)*: The collection to iterate over. 2. `callback` *(Function|String)*: The function called per iteration or property name to group by. 3. `[thisArg]` *(Mixed)*: The `this` binding for the callback. @@ -863,7 +869,7 @@ _.groupBy(['one', 'two', 'three'], 'length'); ### `_.has(object, property)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2382 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2537 "View in source") [Ⓣ][1] Checks if the specified object `property` exists and is a direct property, instead of an inherited property. @@ -888,7 +894,7 @@ _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b'); ### `_.identity(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2995 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3154 "View in source") [Ⓣ][1] This function returns the first argument passed to it. Note: It is used throughout Lo-Dash as a default callback. @@ -913,7 +919,7 @@ moe === _.identity(moe); ### `_.indexOf(array, value [, fromIndex=0])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L1146 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1336 "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 `isSorted` will run a faster binary search. @@ -945,7 +951,7 @@ _.indexOf([1, 1, 2, 2, 3, 3], 2, true); ### `_.initial(array [, n, guard])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L1186 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1376 "View in source") [Ⓣ][1] Gets all but the last value of `array`. Pass `n` to exclude the last `n` values from the result. @@ -971,7 +977,7 @@ _.initial([3, 2, 1]); ### `_.intersection([array1, array2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L1207 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1397 "View in source") [Ⓣ][1] Computes the intersection of all the passed-in arrays. @@ -995,12 +1001,12 @@ _.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]); ### `_.invoke(collection, methodName [, arg1, arg2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L717 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L887 "View in source") [Ⓣ][1] Invokes the method named by `methodName` on each element in the `collection`. 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`. #### Arguments -1. `collection` *(Array|Object)*: The collection to iterate over. +1. `collection` *(Array|Object|String)*: The collection to iterate over. 2. `methodName` *(Function|String)*: The name of the method to invoke or the function invoked per iteration. 3. `[arg1, arg2, ...]` *(Mixed)*: Arguments to invoke the method with. @@ -1024,7 +1030,7 @@ _.invoke([123, 456], String.prototype.split, ''); ### `_.isArguments(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2402 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2557 "View in source") [Ⓣ][1] Checks if `value` is an `arguments` object. @@ -1051,7 +1057,7 @@ _.isArguments([1, 2, 3]); ### `_.isArray(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2428 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2583 "View in source") [Ⓣ][1] Checks if `value` is an array. @@ -1078,7 +1084,7 @@ _.isArray([1, 2, 3]); ### `_.isBoolean(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2445 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2600 "View in source") [Ⓣ][1] Checks if `value` is a boolean *(`true` or `false`)* value. @@ -1102,7 +1108,7 @@ _.isBoolean(null); ### `_.isDate(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2462 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2617 "View in source") [Ⓣ][1] Checks if `value` is a date. @@ -1126,7 +1132,7 @@ _.isDate(new Date); ### `_.isElement(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2479 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2634 "View in source") [Ⓣ][1] Checks if `value` is a DOM element. @@ -1150,7 +1156,7 @@ _.isElement(document.body); ### `_.isEmpty(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2500 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2658 "View in source") [Ⓣ][1] Checks if `value` is empty. Arrays or strings with a length of `0` and objects with no own enumerable properties are considered "empty". @@ -1167,6 +1173,9 @@ _.isEmpty([1, 2, 3]); _.isEmpty({}); // => true + +_.isEmpty(''); +// => true ~~~ * * * @@ -1177,7 +1186,7 @@ _.isEmpty({}); ### `_.isEqual(a, b [, stack])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2534 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2692 "View in source") [Ⓣ][1] Performs a deep comparison between two values to determine if they are equivalent to each other. @@ -1209,7 +1218,7 @@ _.isEqual(moe, clone); ### `_.isFinite(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2695 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2853 "View in source") [Ⓣ][1] Checks if `value` is a finite number. Note: This is not the same as native `isFinite`, which will return true for booleans and other values. See http://es5.github.com/#x15.1.2.5. @@ -1239,7 +1248,7 @@ _.isFinite(Infinity); ### `_.isFunction(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2712 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2870 "View in source") [Ⓣ][1] Checks if `value` is a function. @@ -1263,7 +1272,7 @@ _.isFunction(''.concat); ### `_.isNaN(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2764 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2922 "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. @@ -1296,7 +1305,7 @@ _.isNaN(undefined); ### `_.isNull(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2787 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2945 "View in source") [Ⓣ][1] Checks if `value` is `null`. @@ -1323,7 +1332,7 @@ _.isNull(undefined); ### `_.isNumber(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2804 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2962 "View in source") [Ⓣ][1] Checks if `value` is a number. @@ -1347,9 +1356,9 @@ _.isNumber(8.4 * 5; ### `_.isObject(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2733 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2891 "View in source") [Ⓣ][1] -Checks if `value` is the language type of Object. *(e.g. arrays, functions, objects, regexps, `new Number(0)*`, and `new String('')`) +Checks if `value` is the language type of Object. *(e.g. arrays, functions, objects, regexps, `new Number(0)`, and `new String('')`)* #### Arguments 1. `value` *(Mixed)*: The value to check. @@ -1374,7 +1383,7 @@ _.isObject(1); ### `_.isRegExp(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2821 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2979 "View in source") [Ⓣ][1] Checks if `value` is a regular expression. @@ -1398,7 +1407,7 @@ _.isRegExp(/moe/); ### `_.isString(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2838 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2996 "View in source") [Ⓣ][1] Checks if `value` is a string. @@ -1422,7 +1431,7 @@ _.isString('moe'); ### `_.isUndefined(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2856 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3014 "View in source") [Ⓣ][1] Checks if `value` is `undefined`. @@ -1446,7 +1455,7 @@ _.isUndefined(void 0); ### `_.keys(object)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2873 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3031 "View in source") [Ⓣ][1] Produces an array of object`'s own enumerable property names. @@ -1470,7 +1479,7 @@ _.keys({ 'one': 1, 'two': 2, 'three': 3 }); ### `_.last(array [, n, guard])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L1245 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1435 "View in source") [Ⓣ][1] Gets the last value of the `array`. Pass `n` to return the lasy `n` values of the `array`. @@ -1496,7 +1505,7 @@ _.last([3, 2, 1]); ### `_.lastIndexOf(array, value [, fromIndex=array.length-1])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L1271 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1461 "View in source") [Ⓣ][1] Gets the index at which the last occurrence of `value` is found using strict equality for comparisons, i.e. `===`. @@ -1525,12 +1534,12 @@ _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3); ### `_.map(collection [, callback=identity, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L750 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L924 "View in source") [Ⓣ][1] Produces a new array of values by mapping each element in the `collection` through a transformation `callback`. The `callback` is bound to `thisArg` and invoked with `3` arguments; for arrays they are *(value, index, array)* and for objects they are *(value, key, object)*. #### Arguments -1. `collection` *(Array|Object)*: The collection to iterate over. +1. `collection` *(Array|Object|String)*: The collection to iterate over. 2. `[callback=identity]` *(Function)*: The function called per iteration. 3. `[thisArg]` *(Mixed)*: The `this` binding for the callback. @@ -1554,7 +1563,7 @@ _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; }); ### `_.max(array [, callback, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L1311 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1501 "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 `3` arguments; *(value, index, array)*. @@ -1586,7 +1595,7 @@ _.max(stooges, function(stooge) { return stooge.age; }); ### `_.memoize(func [, resolver])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2075 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2230 "View in source") [Ⓣ][1] Creates a new 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. @@ -1612,7 +1621,7 @@ var fibonacci = _.memoize(function(n) { ### `_.min(array [, callback, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L1361 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1551 "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 `3` arguments; *(value, index, array)*. @@ -1638,7 +1647,7 @@ _.min([10, 5, 100, 2, 1000]); ### `_.mixin(object)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L3021 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3180 "View in source") [Ⓣ][1] Adds functions properties of `object` to the `lodash` function and chainable wrapper. @@ -1668,7 +1677,7 @@ _('larry').capitalize(); ### `_.noConflict()` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L3052 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3211 "View in source") [Ⓣ][1] Reverts the '_' variable to its previous value and returns a reference to the `lodash` function. @@ -1688,7 +1697,7 @@ var lodash = _.noConflict(); ### `_.once(func)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2101 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2256 "View in source") [Ⓣ][1] Creates a new function that is restricted to one execution. Repeat calls to the function will return the value of the first call. @@ -1714,7 +1723,7 @@ initialize(); ### `_.partial(func [, arg1, arg2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2134 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2289 "View in source") [Ⓣ][1] Creates a new function that, when called, invokes `func` with any additional `partial` arguments prepended to those passed to the partially applied function. This method is similar `bind`, except it does **not** alter the `this` binding. @@ -1741,7 +1750,7 @@ hi('moe'); ### `_.pick(object [, prop1, prop2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2895 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3053 "View in source") [Ⓣ][1] Creates an object composed of the specified properties. Property names may be specified as individual arguments or as arrays of property names. @@ -1766,12 +1775,12 @@ _.pick({ 'name': 'moe', 'age': 40, 'userid': 'moe1' }, 'name', 'age'); ### `_.pluck(collection, property)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L773 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L947 "View in source") [Ⓣ][1] Retrieves the value of a specified property from all elements in the `collection`. #### Arguments -1. `collection` *(Array|Object)*: The collection to iterate over. +1. `collection` *(Array|Object|String)*: The collection to iterate over. 2. `property` *(String)*: The property to pluck. #### Returns @@ -1797,7 +1806,7 @@ _.pluck(stooges, 'name'); ### `_.range([start=0], end [, step=1])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L1422 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1612 "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. @@ -1835,12 +1844,12 @@ _.range(0); ### `_.reduce(collection, callback [, accumulator, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L802 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L976 "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, array)* and for objects they are *(accumulator, value, key, object)*. #### Arguments -1. `collection` *(Array|Object)*: The collection to iterate over. +1. `collection` *(Array|Object|String)*: The collection to iterate over. 2. `callback` *(Function)*: The function called per iteration. 3. `[accumulator]` *(Mixed)*: Initial value of the accumulator. 4. `[thisArg]` *(Mixed)*: The `this` binding for the callback. @@ -1862,12 +1871,12 @@ var sum = _.reduce([1, 2, 3], function(memo, num) { return memo + num; }); ### `_.reduceRight(collection, callback [, accumulator, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L839 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1013 "View in source") [Ⓣ][1] The right-associative version of `_.reduce`. #### Arguments -1. `collection` *(Array|Object)*: The collection to iterate over. +1. `collection` *(Array|Object|String)*: The collection to iterate over. 2. `callback` *(Function)*: The function called per iteration. 3. `[accumulator]` *(Mixed)*: Initial value of the accumulator. 4. `[thisArg]` *(Mixed)*: The `this` binding for the callback. @@ -1890,12 +1899,12 @@ var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []); ### `_.reject(collection [, callback=identity, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L890 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1068 "View in source") [Ⓣ][1] The opposite of `_.filter`, this method returns the values of a `collection` that `callback` does **not** return truthy for. #### Arguments -1. `collection` *(Array|Object)*: The collection to iterate over. +1. `collection` *(Array|Object|String)*: The collection to iterate over. 2. `[callback=identity]` *(Function)*: The function called per iteration. 3. `[thisArg]` *(Mixed)*: The `this` binding for the callback. @@ -1916,7 +1925,7 @@ var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); ### `_.rest(array [, n, guard])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L1458 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1649 "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. @@ -1942,7 +1951,7 @@ _.rest([3, 2, 1]); ### `_.result(object, property)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L3084 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3243 "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. @@ -1977,7 +1986,7 @@ _.result(object, 'stuff'); ### `_.shuffle(array)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L1479 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1670 "View in source") [Ⓣ][1] Produces a new array of shuffled `array` values, using a version of the Fisher-Yates shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle. @@ -2001,7 +2010,7 @@ _.shuffle([1, 2, 3, 4, 5, 6]); ### `_.size(value)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2934 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3092 "View in source") [Ⓣ][1] Gets the size of `value` by returning `value.length` if `value` is a string or array, or the number of own enumerable properties if `value` is an object. @@ -2031,12 +2040,12 @@ _.size('curly'); ### `_.some(collection [, callback=identity, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L914 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1092 "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 `3` arguments; for arrays they are *(value, index, array)* and for objects they are *(value, key, object)*. #### Arguments -1. `collection` *(Array|Object)*: The collection to iterate over. +1. `collection` *(Array|Object|String)*: The collection to iterate over. 2. `[callback=identity]` *(Function)*: The function called per iteration. 3. `[thisArg]` *(Mixed)*: The `this` binding for the callback. @@ -2056,13 +2065,13 @@ _.some([null, 0, 'yes', false]); -### `_.sortBy(array, callback [, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L1521 "View in source") [Ⓣ][1] +### `_.sortBy(collection, callback [, thisArg])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1125 "View in source") [Ⓣ][1] -Produces a new sorted array, ranked in ascending order by the results of running each element of `array` through `callback`. The `callback` is bound to `thisArg` and invoked with `3` arguments; *(value, index, array)*. The `callback` argument may also be the name of a property to sort by *(e.g. 'length')*. +Produces a new sorted array, sorted in ascending order by the results of running each element of `collection` through a transformation `callback`. The `callback` is bound to `thisArg` and invoked with `3` arguments; for arrays they are *(value, index, array)* and for objects they are *(value, key, object)*. The `callback` argument may also be the name of a property to sort by *(e.g. 'length')*. #### Arguments -1. `array` *(Array)*: The array to iterate over. +1. `collection` *(Array|Object|String)*: The collection to iterate over. 2. `callback` *(Function|String)*: The function called per iteration or property name to sort by. 3. `[thisArg]` *(Mixed)*: The `this` binding for the callback. @@ -2089,7 +2098,7 @@ _.sortBy(['larry', 'brendan', 'moe'], 'length'); ### `_.sortedIndex(array, value [, callback=identity, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L1595 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1722 "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 `1` argument; *(value)*. @@ -2130,7 +2139,7 @@ _.sortedIndex(['twenty', 'thirty', 'fourty'], 'thirty-five', function(word) { ### `_.tap(value, interceptor)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L3318 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3545 "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. @@ -2160,9 +2169,9 @@ _.chain([1,2,3,200]) ### `_.template(text, data, options)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L3145 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3303 "View in source") [Ⓣ][1] -A micro-templating method, similar to John Resig's implementation. Lo-Dash templating handles arbitrary delimiters, preserves whitespace, and correctly escapes quotes within interpolated code. +A micro-templating method that handles arbitrary delimiters, preserves whitespace, and correctly escapes quotes within interpolated code. #### Arguments 1. `text` *(String)*: The template text. @@ -2219,7 +2228,7 @@ _.template('<%= data.hasWith %>', { 'hasWith': 'no' }, { 'variable': 'data' }); ### `_.throttle(func, wait)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2170 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2325 "View in source") [Ⓣ][1] Creates a new 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. @@ -2244,7 +2253,7 @@ jQuery(window).on('scroll', throttled); ### `_.times(n, callback [, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L3234 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3461 "View in source") [Ⓣ][1] Executes the `callback` function `n` times. The `callback` is bound to `thisArg` and invoked with `1` argument; *(index)*. @@ -2270,12 +2279,12 @@ _.times(3, function() { this.grantWish(); }, genie); ### `_.toArray(collection)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L933 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1168 "View in source") [Ⓣ][1] Converts the `collection`, into an array. Useful for converting the `arguments` object. #### Arguments -1. `collection` *(Array|Object)*: The collection to convert. +1. `collection` *(Array|Object|String)*: The collection to convert. #### Returns *(Array)*: Returns the new converted array. @@ -2294,7 +2303,7 @@ Converts the `collection`, into an array. Useful for converting the `arguments` ### `_.union([array1, array2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L1635 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1762 "View in source") [Ⓣ][1] Computes the union of the passed-in arrays. @@ -2318,7 +2327,7 @@ _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]); ### `_.uniq(array [, isSorted=false, callback=identity, thisArg])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L1680 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1807 "View in source") [Ⓣ][1] Produces 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 value of `array` is passed through a transformation `callback` before uniqueness is computed. The `callback` is bound to `thisArg` and invoked with `3` arguments; *(value, index, array)*. @@ -2336,7 +2345,7 @@ Produces a duplicate-value-free version of the `array` using strict equality for _.uniq([1, 2, 1, 3, 1]); // => [1, 2, 3] -_.uiq([1, 1, 2, 2, 3], true); +_.uniq([1, 1, 2, 2, 3], true); // => [1, 2, 3] _.uniq([1, 2, 1.5, 3, 2.5], function(num) { return Math.floor(num); }); @@ -2354,7 +2363,7 @@ _.uniq([1, 2, 1.5, 3, 2.5], function(num) { return this.floor(num); }, Math); ### `_.uniqueId([prefix])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L3261 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3488 "View in source") [Ⓣ][1] Generates a unique id. If `prefix` is passed, the id will be appended to it. @@ -2378,7 +2387,7 @@ _.uniqueId('contact_'); ### `_.values(object)` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2954 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3113 "View in source") [Ⓣ][1] Produces an array of `object`'s own enumerable property values. @@ -2402,7 +2411,7 @@ _.values({ 'one': 1, 'two': 2, 'three': 3 }); ### `_.without(array [, value1, value2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L1729 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1856 "View in source") [Ⓣ][1] Produces a new array with all occurrences of the passed values removed using strict equality for comparisons, i.e. `===`. @@ -2427,7 +2436,7 @@ _.without([1, 2, 1, 0, 3, 1, 4], 0, 1); ### `_.wrap(func, wrapper [, arg1, arg2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L2222 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2377 "View in source") [Ⓣ][1] Create a new function that passes the `func` function to the `wrapper` function as its first argument. Additional arguments are appended to those passed to the `wrapper` function. @@ -2457,9 +2466,9 @@ hello(); ### `_.zip([array1, array2, ...])` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L1762 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1888 "View in source") [Ⓣ][1] -Merges together the values of each of the arrays with the value at the corresponding position. 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. +Merges 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. #### Arguments 1. `[array1, array2, ...]` *(Array)*: Arrays to process. @@ -2478,6 +2487,30 @@ _.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]); + + +### `_.zipObject(keys)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1917 "View in source") [Ⓣ][1] + +Merges an array of `keys` and an array of `values` into a single object. + +#### Arguments +1. `keys` *(Array)*: The array of keys. + +#### Returns +*(Object)*: Returns an object composed of the given keys and corresponding values. + +#### Example +~~~ js +_.zipObject(['moe', 'larry', 'curly'], [30, 40, 50]); +// => { 'moe': 30, 'larry': 40, 'curly': 50 } +~~~ + +* * * + + + + @@ -2488,7 +2521,7 @@ _.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]); ### `_.prototype.chain()` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L3336 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3563 "View in source") [Ⓣ][1] Enables method chaining on the wrapper object. @@ -2509,7 +2542,7 @@ _([1, 2, 3]).value(); ### `_.prototype.value()` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L3353 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3580 "View in source") [Ⓣ][1] Extracts the wrapped value. @@ -2537,9 +2570,9 @@ _([1, 2, 3]).value(); ### `_.templateSettings` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L168 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L225 "View in source") [Ⓣ][1] -*(Object)*: By default, Lo-Dash uses ERB-style template delimiters, change the following template settings to use alternative delimiters. +*(Object)*: By default, Lo-Dash uses embedded Ruby *(ERB)* style template delimiters, change the following template settings to use alternative delimiters. * * * @@ -2549,7 +2582,7 @@ _([1, 2, 3]).value(); ### `_.templateSettings.escape` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L177 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L234 "View in source") [Ⓣ][1] *(RegExp)*: Used to detect `data` property values to be HTML-escaped. @@ -2561,7 +2594,7 @@ _([1, 2, 3]).value(); ### `_.templateSettings.evaluate` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L186 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L243 "View in source") [Ⓣ][1] *(RegExp)*: Used to detect code to be evaluated. @@ -2573,7 +2606,7 @@ _([1, 2, 3]).value(); ### `_.templateSettings.interpolate` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L195 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L252 "View in source") [Ⓣ][1] *(RegExp)*: Used to detect `data` property values to inject. @@ -2585,7 +2618,7 @@ _([1, 2, 3]).value(); ### `_.templateSettings.variable` -# [Ⓢ](https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js#L204 "View in source") [Ⓣ][1] +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L261 "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 240404ce79..ef05835cc1 100644 --- a/doc/parse.php +++ b/doc/parse.php @@ -21,8 +21,8 @@ // generate Markdown $markdown = docdown(array( 'path' => '../' . $file, - 'title' => 'Lo-Dash v0.3.2', - 'url' => 'https://github.com/bestiejs/lodash/blob/v0.3.2/lodash.js' + 'title' => 'Lo-Dash v0.4.0', + 'url' => 'https://github.com/bestiejs/lodash/blob/master/lodash.js' )); // save to a .md file diff --git a/lodash.js b/lodash.js index b5fa4b2f29..6ee75ebc7a 100644 --- a/lodash.js +++ b/lodash.js @@ -1,5 +1,5 @@ /*! - * Lo-Dash v0.3.2 + * Lo-Dash v0.4.0 * Copyright 2012 John-David Dalton * Based on Underscore.js 1.3.3, copyright 2009-2012 Jeremy Ashkenas, DocumentCloud Inc. * @@ -8,16 +8,38 @@ ;(function(window, undefined) { 'use strict'; + /** + * Used to cache the last `_.templateSettings.evaluate` delimiter to avoid + * unnecessarily assigning `reEvaluateDelimiter` a new generated regexp. + * Assigned in `_.template`. + */ + var lastEvaluateDelimiter; + + /** + * Used to cache the last template `options.variable` to avoid unnecessarily + * assigning `reDoubleVariable` a new generated regexp. Assigned in `_.template`. + */ + var lastVariable; + + /** + * Used to match potentially incorrect data object references, like `obj.obj`, + * in compiled templates. Assigned in `_.template`. + */ + var reDoubleVariable; + + /** + * Used to match "evaluate" delimiters, including internal delimiters, + * in template text. Assigned in `_.template`. + */ + var reEvaluateDelimiter; + /** Detect free variable `exports` */ var freeExports = typeof exports == 'object' && exports && (typeof global == 'object' && global && global == global.global && (window = global), exports); - /** - * Detect the JScript [[DontEnum]] bug: - * In IE < 9 an objects own properties, shadowing non-enumerable ones, are - * made non-enumerable as well. - */ - var hasDontEnumBug = !{ 'valueOf': 0 }.propertyIsEnumerable('valueOf'); + /** Native prototype shortcuts */ + var ArrayProto = Array.prototype, + ObjectProto = Object.prototype; /** Used to generate unique IDs */ var idCounter = 0; @@ -25,15 +47,33 @@ /** Used to restore the original `_` reference in `noConflict` */ var oldDash = window._; + /** Used to detect delimiter values that should be processed by `tokenizeEvaluate` */ + var reComplexDelimiter = /[-+=!~*%&^<>|{(\/]|\[\D|\b(?:delete|in|instanceof|new|typeof|void)\b/; + + /** Used to match code generated in place of template delimiters */ + var reDelimiterCodeLeading = /^';\n/, + reDelimiterCodeMiddle = /^' \+\n/, + reDelimiterCodeTrailing = /(?:__p \+= '|\+\n')$/; + + /** Used to match empty string literals in compiled template source */ + var reEmptyStringLeading = /\b__p \+= '';/g, + reEmptyStringMiddle = /\b(__p \+?=) '' \+/g, + reEmptyStringTrailing = /(__w?e\(.*?\)|\b__w?t\)) \+\n'';/g; + + /** 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('^' + ({}.valueOf + '') - .replace(/[.*+?^=!:${}()|[\]\/\\]/g, '\\$&') - .replace(/valueOf|for [^\]]+/g, '.+?') + '$'); + var reNative = RegExp('^' + + (ObjectProto.valueOf + '') + .replace(/[.*+?^=!:${}()|[\]\/\\]/g, '\\$&') + .replace(/valueOf|for [^\]]+/g, '.+?') + '$' + ); /** Used to match tokens in template text */ var reToken = /__token__(\d+)/g; - /** Used to match unescaped characters in HTML */ + /** Used to match unescaped characters in strings for inclusion in HTML */ var reUnescapedHtml = /[&<"']/g; /** Used to match unescaped characters in compiled string literals */ @@ -54,6 +94,56 @@ /** Used to store tokenized template text snippets */ var tokenized = []; + /** Native method shortcuts */ + var concat = ArrayProto.concat, + hasOwnProperty = ObjectProto.hasOwnProperty, + push = ArrayProto.push, + propertyIsEnumerable = ObjectProto.propertyIsEnumerable, + slice = ArrayProto.slice, + toString = ObjectProto.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, + nativeKeys = reNative.test(nativeKeys = Object.keys) && nativeKeys; + + /** `Object#toString` result shortcuts */ + var arrayClass = '[object Array]', + boolClass = '[object Boolean]', + dateClass = '[object Date]', + funcClass = '[object Function]', + numberClass = '[object Number]', + regexpClass = '[object RegExp]', + stringClass = '[object String]'; + + /** Timer shortcuts */ + var clearTimeout = window.clearTimeout, + setTimeout = window.setTimeout; + + /** + * Detect the JScript [[DontEnum]] bug: + * In IE < 9 an objects own properties, shadowing non-enumerable ones, are + * made non-enumerable as well. + */ + var hasDontEnumBug = !propertyIsEnumerable.call({ 'valueOf': 0 }, 'valueOf'); + + /** Detect if `Array#slice` cannot be used to convert strings to arrays (e.g. Opera < 10.52) */ + var noArraySliceOnStrings = slice.call('x')[0] != 'x'; + + /** + * 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 `Function#bind` exists and is inferred to be fast (i.e. 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 (i.e. V8, Opera, IE) */ + var isKeysFast = nativeKeys && /^.+$|true/.test(nativeKeys + !!window.attachEvent); + /** Detect if sourceURL syntax is usable without erroring */ try { // Adobe's and Narwhal's JS engines will error @@ -94,39 +184,6 @@ '\u2029': 'u2029' }; - /** Object#toString result shortcuts */ - var arrayClass = '[object Array]', - boolClass = '[object Boolean]', - dateClass = '[object Date]', - funcClass = '[object Function]', - numberClass = '[object Number]', - regexpClass = '[object RegExp]', - stringClass = '[object String]'; - - /** Native prototype shortcuts */ - var ArrayProto = Array.prototype, - ObjectProto = Object.prototype; - - /** Native method shortcuts */ - var concat = ArrayProto.concat, - hasOwnProperty = ObjectProto.hasOwnProperty, - push = ArrayProto.push, - slice = ArrayProto.slice, - toString = ObjectProto.toString; - - /* Used if `Function#bind` exists and is inferred to be fast (i.e. all but V8) */ - var nativeBind = reNative.test(nativeBind = slice.bind) && - /\n|Opera/.test(nativeBind + toString.call(window.opera)) && nativeBind; - - /* Native method shortcuts for methods with the same name as other `lodash` methods */ - var nativeIsArray = reNative.test(nativeIsArray = Array.isArray) && nativeIsArray, - nativeIsFinite = window.isFinite, - nativeKeys = reNative.test(nativeKeys = Object.keys) && nativeKeys; - - /** Timer shortcuts */ - var clearTimeout = window.clearTimeout, - setTimeout = window.setTimeout; - /*--------------------------------------------------------------------------*/ /** @@ -158,8 +215,8 @@ } /** - * By default, Lo-Dash uses ERB-style template delimiters, change the - * following template settings to use alternative delimiters. + * By default, Lo-Dash uses embedded Ruby (ERB) style template delimiters, + * change the following template settings to use alternative delimiters. * * @static * @memberOf _ @@ -215,37 +272,62 @@ */ var iteratorTemplate = template( // assign the `result` variable an initial value - 'var index, result<% if (init) { %> = <%= init %><% } %>;\n' + + 'var result<% if (init) { %> = <%= init %><% } %>;\n' + // add code to exit early or do so if the first argument is falsey '<%= exit %>;\n' + // add code after the exit snippet but before the iteration branches '<%= top %>;\n' + + 'var index, iteratee = <%= iteratee %>;\n' + // the following branch is for iterating arrays and array-like objects '<% if (arrayBranch) { %>' + - 'var length = <%= firstArg %>.length; index = -1;' + - ' <% if (objectBranch) { %>\nif (length === length >>> 0) {<% } %>\n' + + 'var length = iteratee.length; index = -1;' + + ' <% if (objectBranch) { %>\nif (length === length >>> 0) {<% } %>' + + + // add support for accessing string characters by index if needed + ' <% if (noCharByIndex) { %>\n' + + ' if (toString.call(iteratee) == stringClass) {\n' + + ' iteratee = iteratee.split(\'\')\n' + + ' }' + + ' <% } %>\n' + + ' <%= arrayBranch.beforeLoop %>;\n' + - ' while (<%= arrayBranch.loopExp %>) {\n' + - ' <%= arrayBranch.inLoop %>;\n' + + ' while (++index < length) {\n' + + ' <%= arrayBranch.inLoop %>\n' + ' }' + - ' <% if (objectBranch) { %>\n}\n<% }' + - '}' + + ' <% if (objectBranch) { %>\n}<% } %>' + + '<% } %>' + // the following branch is for iterating an object's own/inherited properties - 'if (objectBranch) {' + - ' if (arrayBranch) { %>else {\n<% }' + - ' if (!hasDontEnumBug) { %> var skipProto = typeof <%= iteratedObject %> == \'function\';\n<% } %>' + + '<% if (objectBranch) { %>' + + ' <% if (arrayBranch) { %>\nelse {<% } %>' + + ' <% if (!hasDontEnumBug) { %>\n' + + ' var skipProto = typeof iteratee == \'function\' && \n' + + ' propertyIsEnumerable.call(iteratee, \'prototype\');\n' + + ' <% } %>' + + + // iterate own properties using `Object.keys` if it's fast + ' <% if (isKeysFast && useHas) { %>\n' + + ' var props = nativeKeys(iteratee),\n' + + ' propIndex = -1,\n' + + ' length = props.length;\n\n' + ' <%= objectBranch.beforeLoop %>;\n' + - ' for (<%= objectBranch.loopExp %>) {' + - ' \n<%' + - ' if (hasDontEnumBug) {' + - ' if (useHas) { %> if (<%= hasExp %>) {\n <% } %>' + - ' <%= objectBranch.inLoop %>;<%' + - ' if (useHas) { %>\n }<% }' + + ' while (++propIndex < length) {\n' + + ' index = props[propIndex];\n' + + ' if (!(skipProto && index == \'prototype\')) {\n' + + ' <%= objectBranch.inLoop %>\n' + + ' }\n' + ' }' + - ' else {' + - ' %>' + + + // else using a for-in loop + ' <% } else { %>\n' + + ' <%= objectBranch.beforeLoop %>;\n' + + ' for (index in iteratee) {' + + ' <% if (hasDontEnumBug) { %>\n' + + ' <% if (useHas) { %>if (hasOwnProperty.call(iteratee, index)) {\n <% } %>' + + ' <%= objectBranch.inLoop %>;\n' + + ' <% if (useHas) { %>}<% } %>' + + ' <% } else { %>\n' + // Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1 // (if the prototype or a property on the prototype has been set) @@ -253,30 +335,32 @@ // value to `true`. Because of this Lo-Dash standardizes on skipping // the the `prototype` property of functions regardless of its // [[Enumerable]] value. - ' if (!(skipProto && index == \'prototype\')<% if (useHas) { %> && <%= hasExp %><% } %>) {\n' + - ' <%= objectBranch.inLoop %>;\n' + + ' if (!(skipProto && index == \'prototype\')<% if (useHas) { %> &&\n' + + ' hasOwnProperty.call(iteratee, index)<% } %>) {\n' + + ' <%= objectBranch.inLoop %>\n' + ' }' + - ' <% } %>\n' + + ' <% } %>\n' + ' }' + + ' <% } %>' + // Because IE < 9 can't set the `[[Enumerable]]` attribute of an // existing property and the `constructor` property of a prototype // defaults to non-enumerable, Lo-Dash skips the `constructor` // property when it infers it's iterating over a `prototype` object. - ' <% if (hasDontEnumBug) { %>\n' + - ' var ctor = <%= iteratedObject %>.constructor;\n' + - ' <% for (var k = 0; k < 7; k++) { %>\n' + + ' <% if (hasDontEnumBug) { %>\n\n' + + ' var ctor = iteratee.constructor;\n' + + ' <% for (var k = 0; k < 7; k++) { %>\n' + ' index = \'<%= shadowed[k] %>\';\n' + ' if (<%' + ' if (shadowed[k] == \'constructor\') {' + - ' %>!(ctor && ctor.prototype === <%= iteratedObject %>) && <%' + - ' } %><%= hasExp %>) {\n' + - ' <%= objectBranch.inLoop %>;\n' + - ' }<%' + - ' }' + - ' }' + - ' if (arrayBranch) { %>\n}<% }' + - '} %>\n' + + ' %>!(ctor && ctor.prototype === iteratee) && <%' + + ' } %>hasOwnProperty.call(iteratee, index)) {\n' + + ' <%= objectBranch.inLoop %>\n' + + ' }' + + ' <% } %>' + + ' <% } %>' + + ' <% if (arrayBranch) { %>\n}<% } %>' + + '<% } %>\n' + // add code to the bottom of the iteration function '<%= bottom %>;\n' + @@ -286,7 +370,8 @@ /** * Reusable iterator options shared by - * `every`, `filter`, `find`, `forEach`, `forIn`, `forOwn`, `map`, `reject`, and `some`. + * `every`, `filter`, `find`, `forEach`, `forIn`, `forOwn`, `groupBy`, `map`, + * `reject`, `some`, and `sortBy`. */ var baseIteratorOptions = { 'args': 'collection, callback, thisArg', @@ -298,13 +383,13 @@ 'else if (thisArg) {\n' + ' callback = iteratorBind(callback, thisArg)\n' + '}', - 'inLoop': 'callback(collection[index], index, collection)' + 'inLoop': 'callback(iteratee[index], index, collection)' }; /** Reusable iterator options for `every` and `some` */ var everyIteratorOptions = { 'init': 'true', - 'inLoop': 'if (!callback(collection[index], index, collection)) return !result' + 'inLoop': 'if (!callback(iteratee[index], index, collection)) return !result' }; /** Reusable iterator options for `defaults` and `extend` */ @@ -315,16 +400,16 @@ 'for (var source, sourceIndex = 1, length = arguments.length; sourceIndex < length; sourceIndex++) {\n' + ' source = arguments[sourceIndex];\n' + (hasDontEnumBug ? ' if (source) {' : ''), - 'loopExp': 'index in source', + 'iteratee': 'source', 'useHas': false, - 'inLoop': 'object[index] = source[index]', + 'inLoop': 'result[index] = iteratee[index]', 'bottom': (hasDontEnumBug ? ' }\n' : '') + '}' }; /** Reusable iterator options for `filter` and `reject` */ var filterIteratorOptions = { 'init': '[]', - 'inLoop': 'callback(collection[index], index, collection) && result.push(collection[index])' + 'inLoop': 'callback(iteratee[index], index, collection) && result.push(iteratee[index])' }; /** Reusable iterator options for `find`, `forEach`, `forIn`, and `forOwn` */ @@ -339,17 +424,17 @@ } }; - /** Reusable iterator options for `invoke`, `map`, and `pluck` */ + /** Reusable iterator options for `invoke`, `map`, `pluck`, and `sortBy` */ var mapIteratorOptions = { 'init': '', 'exit': 'if (!collection) return []', 'beforeLoop': { 'array': 'result = Array(length)', - 'object': 'result = []' + 'object': 'result = ' + (isKeysFast ? 'Array(length)' : '[]') }, 'inLoop': { - 'array': 'result[index] = callback(collection[index], index, collection)', - 'object': 'result.push(callback(collection[index], index, collection))' + 'array': 'result[index] = callback(iteratee[index], index, collection)', + 'object': 'result' + (isKeysFast ? '[propIndex] = ' : '.push') + '(callback(iteratee[index], index, collection))' } }; @@ -377,8 +462,8 @@ * beforeLoop - A string or object containing an "array" or "object" property * of code to execute before the array or object loops. * - * loopExp - A string or object containing an "array" or "object" property - * of code to execute as the array or object loop expression. + * iteratee - A string or object containing an "array" or "object" property + * of the variable to be iterated in the loop expression. * * useHas - A boolean to specify whether or not to use `hasOwnProperty` checks * in the object loop. @@ -404,7 +489,7 @@ 'exit': '', 'init': '', 'top': '', - 'arrayBranch': { 'beforeLoop': '', 'loopExp': '++index < length' }, + 'arrayBranch': { 'beforeLoop': '' }, 'objectBranch': { 'beforeLoop': '' } }; @@ -413,7 +498,7 @@ for (prop in object) { value = (value = object[prop]) == null ? '' : value; // keep this regexp explicit for the build pre-process - if (/beforeLoop|loopExp|inLoop/.test(prop)) { + if (/beforeLoop|inLoop/.test(prop)) { if (typeof value == 'string') { value = { 'array': value, 'object': value }; } @@ -424,45 +509,65 @@ } } } - // set additional template data values + // set additional template `data` values var args = data.args, - arrayBranch = data.arrayBranch, - objectBranch = data.objectBranch, firstArg = /^[^,]+/.exec(args)[0], - loopExp = objectBranch.loopExp, - iteratedObject = /\S+$/.exec(loopExp || firstArg)[0]; + iteratee = (data.iteratee = data.iteratee || firstArg); data.firstArg = firstArg; data.hasDontEnumBug = hasDontEnumBug; - data.hasExp = 'hasOwnProperty.call(' + iteratedObject + ', index)'; - data.iteratedObject = iteratedObject; + data.isKeysFast = isKeysFast; data.shadowed = shadowed; data.useHas = data.useHas !== false; + if (!('noCharByIndex' in data)) { + data.noCharByIndex = noCharByIndex; + } if (!data.exit) { data.exit = 'if (!' + firstArg + ') return result'; } - if (firstArg == 'object' || !arrayBranch.inLoop) { + if (firstArg != 'collection' || !data.arrayBranch.inLoop) { data.arrayBranch = null; } - if (!loopExp) { - objectBranch.loopExp = 'index in ' + iteratedObject; - } // create the function factory var factory = Function( - 'arrayClass, funcClass, hasOwnProperty, identity, iteratorBind, objectTypes, ' + - 'slice, stringClass, toString, undefined', + 'arrayClass, compareAscending, funcClass, hasOwnProperty, identity, ' + + 'iteratorBind, objectTypes, nativeKeys, propertyIsEnumerable, ' + + 'slice, stringClass, toString', '"use strict"; return function(' + args + ') {\n' + iteratorTemplate(data) + '\n}' ); // return the compiled function return factory( - arrayClass, funcClass, hasOwnProperty, identity, iteratorBind, objectTypes, - slice, stringClass, toString + arrayClass, compareAscending, funcClass, hasOwnProperty, identity, + iteratorBind, objectTypes, nativeKeys, propertyIsEnumerable, slice, + stringClass, toString ); } /** - * Used by `template()` to replace tokens with their corresponding code snippets. + * Used by `sortBy` to compare transformed values of `collection`, 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 `-1` if `a` < `b`, `0` if `a` == `b`, or `1` if `a` > `b`. + */ + function compareAscending(a, b) { + a = a.criteria; + b = b.criteria; + + if (a === undefined) { + return 1; + } + if (b === undefined) { + return -1; + } + return a < b ? -1 : a > b ? 1 : 0; + } + + /** + * Used by `template` to replace tokens with their corresponding code snippets. * * @private * @param {String} match The matched token. @@ -474,7 +579,7 @@ } /** - * Used by `template()` to escape characters for inclusion in compiled + * Used by `template` to escape characters for inclusion in compiled * string literals. * * @private @@ -486,7 +591,7 @@ } /** - * Used by `escape()` to escape characters for inclusion in HTML. + * Used by `escape` to escape characters for inclusion in HTML. * * @private * @param {String} match The matched character to escape. @@ -530,13 +635,13 @@ */ var shimKeys = createIterator({ 'args': 'object', - 'exit': 'if (!objectTypes[typeof object] || object === null) throw TypeError()', + 'exit': 'if (!(object && objectTypes[typeof object])) throw TypeError()', 'init': '[]', 'inLoop': 'result.push(index)' }); /** - * Used by `template()` to replace "escape" template delimiters with tokens. + * Used by `template` to replace "escape" template delimiters with tokens. * * @private * @param {String} match The matched template delimiter. @@ -544,36 +649,53 @@ * @returns {String} Returns a token. */ function tokenizeEscape(match, value) { + if (reComplexDelimiter.test(value)) { + return ''; + } var index = tokenized.length; - tokenized[index] = "'+\n_.escape(" + value + ") +\n'"; + tokenized[index] = "' +\n__e(" + value + ") +\n'"; return token + index; } /** - * Used by `template()` to replace "interpolate" template delimiters with tokens. + * Used by `template` to replace "evaluate" template delimiters, or complex + * "escape" and "interpolate" delimiters, with tokens. * * @private * @param {String} match The matched template delimiter. * @param {String} value The delimiter value. + * @param {String} escapeValue The "escape" delimiter value. + * @param {String} interpolateValue The "interpolate" delimiter value. * @returns {String} Returns a token. */ - function tokenizeInterpolate(match, value) { + function tokenizeEvaluate(match, value, escapeValue, interpolateValue) { var index = tokenized.length; - tokenized[index] = "'+\n((__t = (" + value + ")) == null ? '' : __t) +\n'"; + if (value) { + tokenized[index] = "';\n" + value + ";\n__p += '" + } + else if (escapeValue) { + tokenized[index] = "' +\n__we(" + escapeValue + ") +\n'"; + } + else if (interpolateValue) { + tokenized[index] = "' +\n((__wt = (" + interpolateValue + ")) == null ? '' : __wt) +\n'"; + } return token + index; } /** - * Used by `template()` to replace "evaluate" template delimiters with tokens. + * Used by `template` to replace "interpolate" template delimiters with tokens. * * @private * @param {String} match The matched template delimiter. * @param {String} value The delimiter value. * @returns {String} Returns a token. */ - function tokenizeEvaluate(match, value) { + function tokenizeInterpolate(match, value) { + if (reComplexDelimiter.test(value)) { + return ''; + } var index = tokenized.length; - tokenized[index] = "';\n" + value + ";\n__p += '"; + tokenized[index] = "' +\n((__t = (" + value + ")) == null ? '' : __t) +\n'"; return token + index; } @@ -587,18 +709,28 @@ * @memberOf _ * @alias include * @category Collections - * @param {Array|Object} collection The collection to iterate over. + * @param {Array|Object|String} collection The collection to iterate over. * @param {Mixed} target The value to check for. * @returns {Boolean} Returns `true` if `target` value is found, else `false`. * @example * * _.contains([1, 2, 3], 3); * // => true + * + * _.contains({ 'name': 'moe', 'age': 40 }, 'moe'); + * // => true + * + * _.contains('curly', 'ur'); + * // => true */ var contains = createIterator({ 'args': 'collection, target', 'init': 'false', - 'inLoop': 'if (collection[index] === target) return true' + 'noCharByIndex': false, + 'beforeLoop': { + 'array': 'if (toString.call(iteratee) == stringClass) return collection.indexOf(target) > -1' + }, + 'inLoop': 'if (iteratee[index] === target) return true' }); /** @@ -611,7 +743,7 @@ * @memberOf _ * @alias all * @category Collections - * @param {Array|Object} collection The collection to iterate over. + * @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 for the callback. * @returns {Boolean} Returns `true` if all values pass the callback check, else `false`. @@ -632,7 +764,7 @@ * @memberOf _ * @alias select * @category Collections - * @param {Array|Object} collection The collection to iterate over. + * @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 for the callback. * @returns {Array} Returns a new array of values that passed callback check. @@ -654,7 +786,7 @@ * @memberOf _ * @alias detect * @category Collections - * @param {Array|Object} collection The collection to iterate over. + * @param {Array|Object|String} collection The collection to iterate over. * @param {Function} callback The function called per iteration. * @param {Mixed} [thisArg] The `this` binding for the callback. * @returns {Mixed} Returns the value that passed the callback check, else `undefined`. @@ -665,7 +797,7 @@ */ var find = createIterator(baseIteratorOptions, forEachIteratorOptions, { 'init': '', - 'inLoop': 'if (callback(collection[index], index, collection)) return collection[index]' + 'inLoop': 'if (callback(iteratee[index], index, collection)) return iteratee[index]' }); /** @@ -678,7 +810,7 @@ * @memberOf _ * @alias each * @category Collections - * @param {Array|Object} collection The collection to iterate over. + * @param {Array|Object|String} collection The collection to iterate over. * @param {Function} callback The function called per iteration. * @param {Mixed} [thisArg] The `this` binding for the callback. * @returns {Array|Object} Returns the `collection`. @@ -692,6 +824,44 @@ */ var forEach = createIterator(baseIteratorOptions, forEachIteratorOptions); + /** + * Splits `collection` into sets, grouped by the result of running each value + * through `callback`. The `callback` is bound to `thisArg` and invoked with + * 3 arguments; for arrays they are (value, index, array) and for objects they + * are (value, key, object). The `callback` argument may also be the name of a + * property to group by. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Function|String} callback The function called per iteration or + * property name to group by. + * @param {Mixed} [thisArg] The `this` binding for the callback. + * @returns {Object} Returns an object of grouped values. + * @example + * + * _.groupBy([1.3, 2.1, 2.4], function(num) { return Math.floor(num); }); + * // => { '1': [1.3], '2': [2.1, 2.4] } + * + * _.groupBy([1.3, 2.1, 2.4], function(num) { return this.floor(num); }, Math); + * // => { '1': [1.3], '2': [2.1, 2.4] } + * + * _.groupBy(['one', 'two', 'three'], 'length'); + * // => { '3': ['one', 'two'], '5': ['three'] } + */ + var groupBy = createIterator(baseIteratorOptions, { + 'init': '{}', + 'top': + 'var prop, isFunc = typeof callback == \'function\';\n' + + 'if (isFunc && thisArg) callback = iteratorBind(callback, thisArg)', + 'inLoop': + 'prop = isFunc\n' + + ' ? callback(iteratee[index], index, collection)\n' + + ' : iteratee[index][callback];\n' + + '(hasOwnProperty.call(result, prop) ? result[prop] : result[prop] = []).push(iteratee[index])' + }); + /** * Invokes the method named by `methodName` on each element in the `collection`. * Additional arguments will be passed to each invoked method. If `methodName` @@ -701,7 +871,7 @@ * @static * @memberOf _ * @category Collections - * @param {Array|Object} collection The collection to iterate over. + * @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. @@ -720,8 +890,12 @@ 'var args = slice.call(arguments, 2),\n' + ' isFunc = typeof methodName == \'function\'', 'inLoop': { - 'array': 'result[index] = (isFunc ? methodName : collection[index][methodName]).apply(collection[index], args)', - 'object': 'result.push((isFunc ? methodName : collection[index][methodName]).apply(collection[index], args))' + 'array': + 'result[index] = (isFunc ? methodName : iteratee[index][methodName])' + + '.apply(iteratee[index], args)', + 'object': + 'result' + (isKeysFast ? '[propIndex] = ' : '.push') + + '((isFunc ? methodName : iteratee[index][methodName]).apply(iteratee[index], args))' } }); @@ -735,7 +909,7 @@ * @memberOf _ * @alias collect * @category Collections - * @param {Array|Object} collection The collection to iterate over. + * @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 for the callback. * @returns {Array} Returns a new array of values returned by the callback. @@ -756,7 +930,7 @@ * @static * @memberOf _ * @category Collections - * @param {Array|Object} collection The collection to iterate over. + * @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 @@ -773,8 +947,8 @@ var pluck = createIterator(mapIteratorOptions, { 'args': 'collection, property', 'inLoop': { - 'array': 'result[index] = collection[index][property]', - 'object': 'result.push(collection[index][property])' + 'array': 'result[index] = iteratee[index][property]', + 'object': 'result' + (isKeysFast ? '[propIndex] = ' : '.push') + '(iteratee[index][property])' } }); @@ -789,7 +963,7 @@ * @memberOf _ * @alias foldl, inject * @category Collections - * @param {Array|Object} collection The collection to iterate over. + * @param {Array|Object|String} collection The collection to iterate over. * @param {Function} callback The function called per iteration. * @param {Mixed} [accumulator] Initial value of the accumulator. * @param {Mixed} [thisArg] The `this` binding for the callback. @@ -810,11 +984,11 @@ }, 'inLoop': { 'array': - 'result = callback(result, collection[index], index, collection)', + 'result = callback(result, iteratee[index], index, collection)', 'object': 'result = noaccum\n' + - ' ? (noaccum = false, collection[index])\n' + - ' : callback(result, collection[index], index, collection)' + ' ? (noaccum = false, iteratee[index])\n' + + ' : callback(result, iteratee[index], index, collection)' } }); @@ -825,7 +999,7 @@ * @memberOf _ * @alias foldr * @category Collections - * @param {Array|Object} collection The collection to iterate over. + * @param {Array|Object|String} collection The collection to iterate over. * @param {Function} callback The function called per iteration. * @param {Mixed} [accumulator] Initial value of the accumulator. * @param {Mixed} [thisArg] The `this` binding for the callback. @@ -848,11 +1022,15 @@ callback = iteratorBind(callback, thisArg); } if (length === length >>> 0) { + var iteratee = noCharByIndex && toString.call(collection) == stringClass + ? collection.split('') + : collection; + if (length && noaccum) { - accumulator = collection[--length]; + accumulator = iteratee[--length]; } while (length--) { - accumulator = callback(accumulator, collection[length], length, collection); + accumulator = callback(accumulator, iteratee[length], length, collection); } return accumulator; } @@ -878,7 +1056,7 @@ * @static * @memberOf _ * @category Collections - * @param {Array|Object} collection The collection to iterate over. + * @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 for the callback. * @returns {Array} Returns a new array of values that did **not** pass the callback check. @@ -902,7 +1080,7 @@ * @memberOf _ * @alias any * @category Collections - * @param {Array|Object} collection The collection to iterate over. + * @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 for the callback. * @returns {Boolean} Returns `true` if any value passes the callback check, else `false`. @@ -916,6 +1094,63 @@ 'inLoop': everyIteratorOptions.inLoop.replace('!', '') }); + + /** + * Produces a new sorted array, sorted in ascending order by the results of + * running each element of `collection` through a transformation `callback`. + * The `callback` is bound to `thisArg` and invoked with 3 arguments; + * for arrays they are (value, index, array) and for objects they are + * (value, key, object). 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 The function called per iteration or + * property name to sort by. + * @param {Mixed} [thisArg] The `this` binding for the callback. + * @returns {Array} Returns a new array of sorted values. + * @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'] + */ + var sortBy = createIterator(baseIteratorOptions, mapIteratorOptions, { + 'top': + 'if (typeof callback == \'string\') {\n' + + ' var prop = callback;\n' + + ' callback = function(collection) { return collection[prop] }\n' + + '}\n' + + 'else if (thisArg) {\n' + + ' callback = iteratorBind(callback, thisArg)\n' + + '}', + 'inLoop': { + 'array': + 'result[index] = {\n' + + ' criteria: callback(iteratee[index], index, collection),\n' + + ' value: iteratee[index]\n' + + '}', + 'object': + 'result' + (isKeysFast ? '[propIndex] = ' : '.push') + '({\n' + + ' criteria: callback(iteratee[index], index, collection),\n' + + ' value: iteratee[index]\n' + + '})' + }, + 'bottom': + 'result.sort(compareAscending);\n' + + 'length = result.length;\n' + + 'while (length--) {\n' + + ' result[length] = result[length].value\n' + + '}' + }); + /** * Converts the `collection`, into an array. Useful for converting the * `arguments` object. @@ -923,7 +1158,7 @@ * @static * @memberOf _ * @category Collections - * @param {Array|Object} collection The collection to convert. + * @param {Array|Object|String} collection The collection to convert. * @returns {Array} Returns the new converted array. * @example * @@ -934,12 +1169,14 @@ if (!collection) { return []; } - if (toString.call(collection.toArray) == funcClass) { + if (collection.toArray && toString.call(collection.toArray) == funcClass) { return collection.toArray(); } var length = collection.length; if (length === length >>> 0) { - return slice.call(collection); + return (noArraySliceOnStrings ? toString.call(collection) == stringClass : typeof collection == 'string') + ? collection.split('') + : slice.call(collection); } return values(collection); } @@ -999,10 +1236,10 @@ } var index = -1, length = array.length, - flattened = concat.apply(result, slice.call(arguments, 1)); + flattened = concat.apply(result, arguments); while (++index < length) { - if (indexOf(flattened, array[index]) < 0) { + if (indexOf(flattened, array[index], length) < 0) { result.push(array[index]); } } @@ -1030,7 +1267,7 @@ */ function first(array, n, guard) { if (array) { - return (n == undefined || guard) ? array[0] : slice.call(array, 0, n); + return (n == null || guard) ? array[0] : slice.call(array, 0, n); } } @@ -1072,53 +1309,6 @@ return result; } - /** - * Splits `array` into sets, grouped by the result of running each value - * through `callback`. The `callback` is bound to `thisArg` and invoked with 3 - * arguments; (value, index, array). The `callback` argument may also be the - * name of a property to group by. - * - * @static - * @memberOf _ - * @category Arrays - * @param {Array} array The array to iterate over. - * @param {Function|String} callback The function called per iteration or - * property name to group by. - * @param {Mixed} [thisArg] The `this` binding for the callback. - * @returns {Object} Returns an object of grouped values. - * @example - * - * _.groupBy([1.3, 2.1, 2.4], function(num) { return Math.floor(num); }); - * // => { '1': [1.3], '2': [2.1, 2.4] } - * - * _.groupBy([1.3, 2.1, 2.4], function(num) { return this.floor(num); }, Math); - * // => { '1': [1.3], '2': [2.1, 2.4] } - * - * _.groupBy(['one', 'two', 'three'], 'length'); - * // => { '3': ['one', 'two'], '5': ['three'] } - */ - function groupBy(array, callback, thisArg) { - var result = {}; - if (!array) { - return result; - } - var prop, - value, - index = -1, - isFunc = typeof callback == 'function', - length = array.length; - - if (isFunc && thisArg) { - callback = iteratorBind(callback, thisArg); - } - while (++index < length) { - value = array[index]; - prop = isFunc ? callback(value, index, array) : value[callback]; - (hasOwnProperty.call(result, prop) ? result[prop] : result[prop] = []).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 @@ -1187,7 +1377,7 @@ if (!array) { return []; } - return slice.call(array, 0, -((n == undefined || guard) ? 1 : n)); + return slice.call(array, 0, -((n == null || guard) ? 1 : n)); } /** @@ -1245,7 +1435,7 @@ function last(array, n, guard) { if (array) { var length = array.length; - return (n == undefined || guard) ? array[length - 1] : slice.call(array, -n || length); + return (n == null || guard) ? array[length - 1] : slice.call(array, -n || length); } } @@ -1421,13 +1611,14 @@ */ function range(start, end, step) { step || (step = 1); - if (arguments.length < 2) { + if (end == null) { end = start || 0; start = 0; } - + // use `Array(length)` so V8 will avoid the slower "dictionary" mode + // http://www.youtube.com/watch?v=XAqIpGU8ZZk#t=16m27s var index = -1, - length = Math.max(Math.ceil((end - start) / step), 0), + length = Math.max(0, Math.ceil((end - start) / step)), result = Array(length); while (++index < length) { @@ -1459,7 +1650,7 @@ if (!array) { return []; } - return slice.call(array, (n == undefined || guard) ? 1 : n); + return slice.call(array, (n == null || guard) ? 1 : n); } /** @@ -1493,70 +1684,6 @@ return result; } - /** - * Produces a new sorted array, ranked in ascending order by the results of - * running each element of `array` through `callback`. The `callback` is - * bound to `thisArg` and invoked with 3 arguments; (value, index, array). The - * `callback` argument may also be the name of a property to sort by (e.g. 'length'). - * - * @static - * @memberOf _ - * @category Arrays - * @param {Array} array The array to iterate over. - * @param {Function|String} callback The function called per iteration or - * property name to sort by. - * @param {Mixed} [thisArg] The `this` binding for the callback. - * @returns {Array} Returns a new array of sorted values. - * @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(array, callback, thisArg) { - if (!array) { - return []; - } - if (typeof callback == 'string') { - var prop = callback; - callback = function(array) { return array[prop]; }; - } else if (thisArg) { - callback = iteratorBind(callback, thisArg); - } - var index = -1, - length = array.length, - result = Array(length); - - while (++index < length) { - result[index] = { - 'criteria': callback(array[index], index, array), - 'value': array[index] - }; - } - result.sort(function(left, right) { - var a = left.criteria, - b = right.criteria; - - if (a === undefined) { - return 1; - } - if (b === undefined) { - return -1; - } - return a < b ? -1 : a > b ? 1 : 0; - }); - - while (length--) { - result[length] = result[length].value; - } - return result; - } - /** * 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 @@ -1668,7 +1795,7 @@ * _.uniq([1, 2, 1, 3, 1]); * // => [1, 2, 3] * - * _.uiq([1, 1, 2, 2, 3], true); + * _.uniq([1, 1, 2, 2, 3], true); * // => [1, 2, 3] * * _.uniq([1, 2, 1.5, 3, 2.5], function(num) { return Math.floor(num); }); @@ -1731,12 +1858,11 @@ if (!array) { return result; } - var excluded = slice.call(arguments, 1), - index = -1, + var index = -1, length = array.length; while (++index < length) { - if (indexOf(excluded, array[index]) < 0) { + if (indexOf(arguments, array[index], 1) < 0) { result.push(array[index]); } } @@ -1744,10 +1870,10 @@ } /** - * Merges together the values of each of the arrays with the value at the - * corresponding position. 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. + * Merges 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 _ @@ -1773,6 +1899,36 @@ return result; } + /** + * Merges an array of `keys` and an array of `values` into a single object. + * + * @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 + * + * _.zipObject(['moe', 'larry', 'curly'], [30, 40, 50]); + * // => { 'moe': 30, 'larry': 40, 'curly': 50 } + */ + function zipObject(keys, values) { + if (!keys) { + return {}; + } + var index = -1, + length = keys.length, + result = {}; + + values || (values = []); + while (++index < length) { + result[keys[index]] = values[index]; + } + return result; + } + /*--------------------------------------------------------------------------*/ /** @@ -1822,24 +1978,24 @@ * * // basic bind * var func = function(greeting) { - * return greeting + ': ' + this.name; + * return greeting + ' ' + this.name; * }; * * func = _.bind(func, { 'name': 'moe' }, 'hi'); * func(); - * // => 'hi: moe' + * // => 'hi moe' * * // lazy bind * var object = { * 'name': 'moe', * 'greet': function(greeting) { - * return greeting + ': ' + this.name; + * return greeting + ' ' + this.name; * } * }; * * var func = _.bind(object, 'greet', 'hi'); * func(); - * // => 'hi: moe' + * // => 'hi moe' * * object.greet = function(greeting) { * return greeting + ', ' + this.name + '!'; @@ -1857,8 +2013,9 @@ methodName = thisArg; thisArg = func; } - // use if `Function#bind` is faster - else if (nativeBind) { + // use `Function#bind` if it exists and is fast + // (in V8 `Function#bind` is slower except when partially applied) + else if (isBindFast || (nativeBind && arguments.length > 2)) { return nativeBind.call.apply(nativeBind, arguments); } @@ -1886,13 +2043,12 @@ // mimic the constructor's `return` behavior // http://es5.github.com/#x13.2.2 var result = func.apply(thisBinding, args); - return objectTypes[typeof result] && result !== null + return result && objectTypes[typeof result] ? result : thisBinding } return func.apply(thisBinding, args); } - return bound; } @@ -1911,8 +2067,7 @@ * * var buttonView = { * 'label': 'lodash', - * 'onClick': function() { alert('clicked: ' + this.label); }, - * 'onHover': function() { console.log('hovering: ' + this.label); } + * 'onClick': function() { alert('clicked: ' + this.label); } * }; * * _.bindAll(buttonView); @@ -1991,7 +2146,7 @@ timeoutId; function delayed() { - timeoutId = undefined; + timeoutId = null; if (!immediate) { func.apply(thisArg, args); } @@ -2176,7 +2331,7 @@ function trailingCall() { lastCalled = new Date; - timeoutId = undefined; + timeoutId = null; func.apply(thisArg, args); } @@ -2246,7 +2401,7 @@ * // => { 'name': 'moe' }; */ function clone(value) { - return objectTypes[typeof value] && value !== null + return value && objectTypes[typeof value] ? (isArray(value) ? value.slice() : extend({}, value)) : value; } @@ -2269,7 +2424,7 @@ * // => { 'flavor': 'chocolate', 'sprinkles': 'rainbow' } */ var defaults = createIterator(extendIteratorOptions, { - 'inLoop': 'if (object[index] == undefined)' + extendIteratorOptions.inLoop + 'inLoop': 'if (result[index] == null) ' + extendIteratorOptions.inLoop }); /** @@ -2360,7 +2515,7 @@ 'args': 'object', 'init': '[]', 'useHas': false, - 'inLoop': 'if (toString.call(object[index]) == funcClass) result.push(index)', + 'inLoop': 'if (toString.call(iteratee[index]) == funcClass) result.push(index)', 'bottom': 'result.sort()' }); @@ -2496,6 +2651,9 @@ * * _.isEmpty({}); * // => true + * + * _.isEmpty(''); + * // => true */ var isEmpty = createIterator({ 'args': 'value', @@ -2539,8 +2697,8 @@ // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } - // a strict comparison is necessary because `null == undefined` - if (a == undefined || b == undefined) { + // a strict comparison is necessary because `undefined == null` + if (a == null || b == null) { return a === b; } // unwrap any wrapped objects @@ -2733,7 +2891,7 @@ function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.com/#x8 - return objectTypes[typeof value] && value !== null; + return value && objectTypes[typeof value]; } /** @@ -2872,7 +3030,7 @@ */ var keys = !nativeKeys ? shimKeys : function(object) { // avoid iterating over the `prototype` property - return typeof object == 'function' + return typeof object == 'function' && propertyIsEnumerable.call(object, 'prototype') ? shimKeys(object) : nativeKeys(object); }; @@ -2932,10 +3090,11 @@ * // => 5 */ function size(value) { - var className = toString.call(value); - return className == arrayClass || className == stringClass - ? value.length - : keys(value).length; + if (!value) { + return 0; + } + var length = value.length; + return length === length >>> 0 ? value.length : keys(value).length; } /** @@ -2954,7 +3113,7 @@ var values = createIterator({ 'args': 'object', 'init': '[]', - 'inLoop': 'result.push(object[index])' + 'inLoop': 'result.push(iteratee[index])' }); /*--------------------------------------------------------------------------*/ @@ -3092,9 +3251,8 @@ } /** - * A micro-templating method, similar to John Resig's implementation. - * Lo-Dash templating handles arbitrary delimiters, preserves whitespace, and - * correctly escapes quotes within interpolated code. + * A micro-templating method that handles arbitrary delimiters, preserves + * whitespace, and correctly escapes quotes within interpolated code. * * @static * @memberOf _ @@ -3143,24 +3301,32 @@ * */ function template(text, data, options) { + // based on John Resig's `tmpl` implementation + // http://ejohn.org/blog/javascript-micro-templating/ + // and Laura Doktorova's doT.js + // https://github.com/olado/doT options || (options = {}); - var result, - defaults = lodash.templateSettings, + var endIndex, + isEvaluating, + startIndex, + result, + useWith, escapeDelimiter = options.escape, evaluateDelimiter = options.evaluate, interpolateDelimiter = options.interpolate, + settings = lodash.templateSettings, variable = options.variable; - // use template defaults if no option is provided + // use default settings if no options object is provided if (escapeDelimiter == null) { - escapeDelimiter = defaults.escape; + escapeDelimiter = settings.escape; } if (evaluateDelimiter == null) { - evaluateDelimiter = defaults.evaluate; + evaluateDelimiter = settings.evaluate; } if (interpolateDelimiter == null) { - interpolateDelimiter = defaults.interpolate; + interpolateDelimiter = settings.interpolate; } // tokenize delimiters to avoid escaping them @@ -3170,28 +3336,85 @@ if (interpolateDelimiter) { text = text.replace(interpolateDelimiter, tokenizeInterpolate); } - if (evaluateDelimiter) { - text = text.replace(evaluateDelimiter, tokenizeEvaluate); + if (evaluateDelimiter != lastEvaluateDelimiter) { + lastEvaluateDelimiter = evaluateDelimiter; + reEvaluateDelimiter = RegExp( + (evaluateDelimiter ? evaluateDelimiter.source : '($^)') + + '||' + , 'g'); + } + startIndex = tokenized.length; + text = text.replace(reEvaluateDelimiter, tokenizeEvaluate); + endIndex = tokenized.length - 1; + isEvaluating = startIndex <= endIndex; + + // if `options.variable` is not specified and the template contains "evaluate" + // delimiters, inject a with-statement around all "evaluate" delimiters to + // add the data object to the top of the scope chain + if (!variable) { + variable = settings.variable || lastVariable || 'obj'; + useWith = isEvaluating; + + if (useWith) { + tokenized[startIndex] = "';\n__with (" + variable + ') {\n' + tokenized[startIndex] + .replace(reDelimiterCodeLeading, '') + .replace(reDelimiterCodeMiddle, '__p += '); + + tokenized[endIndex] = tokenized[endIndex] + .replace(reDelimiterCodeTrailing, '') + "\n}__\n__p += '"; + } } + var strInsertVariable = '$&' + variable + '.', + strDoubleVariable = '$1__d'; + // escape characters that cannot be included in string literals and // detokenize delimiter code snippets - text = "__p='" + text + text = "__p = '" + text .replace(reUnescapedString, escapeStringChar) .replace(reToken, detokenize) + "';\n"; // clear stored code snippets tokenized.length = 0; - // if `options.variable` is not specified, add `data` to the top of the scope chain - if (!variable) { - variable = defaults.variable; - text = 'with (' + variable + ' || {}) {\n' + text + '\n}\n'; - } - + // find the start and end indexes of the with-statement + if (useWith) { + startIndex = text.indexOf('__with'); + endIndex = text.indexOf('}__', startIndex + 10); + } + // memoize `reDoubleVariable` + if (variable != lastVariable) { + lastVariable = variable; + reDoubleVariable = RegExp('([(\\s])' + variable + '\\.' + variable + '\\b', 'g'); + } + // prepend data object references to property names outside of the with-statement + text = (useWith ? text.slice(0, startIndex) : text) + .replace(reInsertVariable, strInsertVariable) + .replace(reDoubleVariable, strDoubleVariable) + + (useWith + ? text.slice(startIndex + 2, endIndex + 1) + + text.slice(endIndex + 3) + .replace(reInsertVariable, strInsertVariable) + .replace(reDoubleVariable, strDoubleVariable) + : '' + ); + + // cleanup code by stripping empty strings + text = (isEvaluating ? text.replace(reEmptyStringLeading, '') : text) + .replace(reEmptyStringMiddle, '$1') + .replace(reEmptyStringTrailing, '$1;'); + + // frame code as the function body text = 'function(' + variable + ') {\n' + - 'var __p, __t, __j = Array.prototype.join;\n' + - 'function print() { __p += __j.call(arguments, \'\') }\n' + + variable + ' || (' + variable + ' = {});\n' + + 'var __p, __t, __wt' + + ', __d = ' + variable + '.' + variable + ' || ' + variable + + ', __e = _.escape, __we = __e' + + (isEvaluating + ? ', __j = Array.prototype.join;\n' + + 'function print() { __p += __j.call(arguments, \'\') }\n' + : ';\n' + ) + text + 'return __p\n}'; @@ -3201,12 +3424,16 @@ text += '\n//@ sourceURL=/lodash/template/source[' + (templateCounter++) + ']'; } - result = Function('_', 'return ' + text)(lodash); + try { + result = Function('_', 'return ' + text)(lodash); + } catch(e) { + result = function() { throw e; }; + } if (data) { return result(data); } - // provide the compiled function's source via its `toString()` method, in + // provide the compiled function's source via its `toString` method, in // supported environments, or the `source` property as a convenience for // build time precompilation result.source = text; @@ -3363,7 +3590,7 @@ * @memberOf _ * @type String */ - lodash.VERSION = '0.3.2'; + lodash.VERSION = '0.4.0'; // assign static methods lodash.after = after; @@ -3449,6 +3676,7 @@ lodash.without = without; lodash.wrap = wrap; lodash.zip = zip; + lodash.zipObject = zipObject; // assign aliases lodash.all = every; diff --git a/lodash.min.js b/lodash.min.js index 63cb9e086f..44ca84a2b5 100644 --- a/lodash.min.js +++ b/lodash.min.js @@ -1,32 +1,35 @@ /*! - Lo-Dash 0.3.2 lodash.com/license + Lo-Dash 0.4.0 lodash.com/license Underscore.js 1.3.3 github.com/documentcloud/underscore/blob/master/LICENSE */ -;(function(e,t){"use strict";function s(e){return"[object Arguments]"==nt.call(e)}function o(e){return new u(e)}function u(e){if(e&&e._wrapped)return e;this._wrapped=e}function a(){for(var e,t,s,o=-1,u=arguments.length,a={e:"",f:"",k:"",q:"",c:{d:"",m:"++l/g -,evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,variable:"obj"};var ft=Function("obj","var __p;with(obj){__p='var l,u';if(k){__p+='='+k};__p+=';'+f+';'+q+';';if(c){__p+='var o='+g+'.length;l=-1;';if(o){__p+='if(o===o>>>0){'};__p+=''+c['d']+';while('+c['m']+'){'+c['j']+'}';if(o){__p+='}'}}if(o){if(c){__p+='else{'}if(!i){__p+='var v=typeof '+l+'==\\'function\\';'};__p+=''+o['d']+';for('+o['m']+'){';if(i){if(r){__p+='if('+h+'){'};__p+=''+o['j']+';';if(r){__p+='}'}}else{__p+='if(!(v&&l==\\'prototype\\')';if(r){__p+='&&'+h};__p+='){'+o['j']+'}'};__p+='}';if(i){__p+='var g='+l+'.constructor;';for(var k=0;k<7;k++){__p+='l=\\''+p[k]+'\\';if(';if(p[k]=='constructor'){__p+='!(g&&g.prototype==='+l+')&&'};__p+=''+h+'){'+o['j']+'}'}}if(c){__p+='}'}};__p+=''+e+';return u'}return __p" -),lt={a:"f,d,B",k:"f",q:"if(!d){d=k}else if(B){d=n(d,B)}",j:"d(f[l],l,f)"},ct={k:"D",j:"if(!d(f[l],l,f))return!u"},ht={a:"r",k:"r",q:"for(var x,y=1,o=arguments.length;ye?t():function(){if(1>--e)return t.apply(this,arguments)}},o.bind=N,o.bindAll=function(e){var t=arguments,n=1;1==t.length&&(n=0,t=Ct(e));for(var r=t.length;nw(i,e[n])&&t.push(e[n]);return t},o.escape=function(e){return e==r?"":(e+"").replace(H,c)},o.every=yt,o.extend=Nt,o.filter=G,o.find=bt,o.first=y,o.flatten=b,o.forEach=wt,o.forIn=ht,o.forOwn=lt,o.functions=Ct,o.groupBy=function(e,t,n){var r={};if(!e)return r;var i,s=-1,o="function"==typeof t,u=e.length;for(o&&n&&(t=h(t,n));++sw(t,n)&&yt(s,function(e){return-1n?Math.max(0,r+n):Math.min(n,r-1))+1);r--;)if(e[r]===t)return r;return-1},o.map=St,o.max=E,o.memoize=function(e,t){var n={};return function(){var r=t?t.apply(this,arguments):arguments[0];return Z.call(n,r)?n[r]:n[r]=e.apply(this,arguments)}},o.min=function(e,t,n){var r=Infinity,i=r;if(!e)return i;var s=-1,o=e.length;if(!t){for(;++sarguments.length&&(t=e||0,e=0);for(var r=-1,i=Math.max(Math.ceil((t-e)/n),0),s=Array(i);++ri?1:0});s--;)o[s]=o[s].b;return o},o.sortedIndex=x,o.tap=function(e,t){return t(e),e},o.template=function(e,t,n){n||(n={});var i;i=o.templateSettings;var s=n.escape,u=n.evaluate,a=n.interpolate,n=n.variable;return s== -r&&(s=i.escape),u==r&&(u=i.evaluate),a==r&&(a=i.interpolate),s&&(e=e.replace(s,d)),a&&(e=e.replace(a,v)),u&&(e=e.replace(u,m)),e="__p='"+e.replace(B,l).replace(P,f)+"';",I.length=0,n||(n=i.variable,e="with("+n+"||{}){"+e+"}"),e="function("+n+"){var __p,__t,__j=Array.prototype.join;function print(){__p+=__j.call(arguments,'')}"+e+"return __p}",i=Function("_","return "+e)(o),t?i(t):(i.source=e,i)},o.throttle=function(e,n){function r(){a=new Date,u=t,e.apply(o,i)}var i,s,o,u,a=0;return function(){var t=new -Date,f=n-(t-a);return i=arguments,o=this,0>=f?(a=t,s=e.apply(o,i)):u||(u=at(r,f)),s}},o.times=function(e,t,n){var r=-1;if(n)for(;++r>>0?tt.call(e):At(e)},o.union=function(){for(var e=-1,t=[],n=Y.apply(t,arguments),r=n.length;++ew(t,n[e])&&t.push(n[e]);return t},o.uniq=T,o.uniqueId=function(e){var t=M++;return e?e+t:t},o.values=At,o.without=function( -e){var t=[];if(!e)return t;for(var n=tt.call(arguments,1),r=-1,i=e.length;++rw(n,e[r])&&t.push(e[r]);return t},o.wrap=function(e,t){return function(){var n=[e];return arguments.length&&et.apply(n,arguments),t.apply(this,n)}},o.zip=function(e){if(!e)return[];for(var t=-1,n=E(xt(arguments,"length")),r=Array(n);++tn;n++)t+="l='"+u.p[n]+"';if(","constructor"==u.p[n]&&(t+="!(h&&h.prototype===n)&&"),t+="j.call(n,l)){"+u.n.i+"}"}u.c&&(t+="}")}return t+=u.e+";return A",Function("c,g,i,j,k,o,u,r,z,C,F,I",'"use strict";return function('+e+"){"+t+"}")(ft,a,ht,et,k,h,Tt,at,nt,rt,vt,it)}function a(e,n){return e=e.a,n=n.a,e===t?1:n===t?-1:en?1:0}function f(e,t){return Y[t]}function l(e){return"\\"+Nt[e]}function c +(e){return xt[e]}function h(e,t){return function(n,r,i){return e.call(t,n,r,i)}}function p(){}function d(e,t){if(F.test(t))return"";var n=Y.length;return Y[n]="'+__e("+t+")+'",G+n}function v(e,t,n,r){return e=Y.length,t?Y[e]="';"+t+";__p+='":n?Y[e]="'+__we("+n+")+'":r&&(Y[e]="'+((__wt=("+r+"))==null?'':__wt)+'"),G+e}function m(e,t){if(F.test(t))return"";var n=Y.length;return Y[n]="'+((__t=("+t+"))==null?'':__t)+'",G+n}function g(e,t,n,r){if(!e)return n;var i=e.length,s=3>arguments +.length;r&&(t=h(t,r));if(i===i>>>0){var o=wt&&it.call(e)==vt?e.split(""):e;for(i&&s&&(n=o[--i]);i--;)n=t(n,o[i],i,e);return n}o=en(e);for((i=o.length)&&s&&(n=e[o[--i]]);i--;)s=o[i],n=t(n,e[s],s,e);return n}function y(e,t,n){if(e)return t==r||n?e[0]:rt.call(e,0,t)}function b(e,t){var n=[];if(!e)return n;for(var r,i=-1,s=e.length;++in?Math.max(0,i+n):n)-1}for(;++ri&&(i=e[s]);return i}for(n&&(t=h(t,n));++sr&&(r=n,i=e[s]);return i}function S(e,t,n){return e?rt.call(e,t==r||n?1:t):[]}function x(e,t,n,r){if(!e)return 0;var i=0,s=e.length;if(n){r&&(n=N(n,r));for(t=n(t);i>>1,n(e[r])>>1,e[r]w(a,r))a.push(r),s.push(e[o]);return s}function N(e,t){function n(){var o=arguments,u=t;return i||(e=t[r]),s.length&&(o=o.length?Z.apply(s,o):s),this instanceof n?(p.prototype=e.prototype,u=new p,(o=e.apply(u,o))&&Tt[typeof o]?o:u):e.apply(u,o)}var r,i=it.call(e)==ht;if(i){if(Et||st&&2++u&&(l=Q[u],!et.call(e,l)||!!(a=et.call +(t,l)&&C(e[l],t[l],s))););}return s.pop(),a}function k(e){return e}function L(e){Ft(Gt(e),function(t){var r=s[t]=e[t];o.prototype[t]=function(){var e=[this._wrapped];return arguments.length&&tt.apply(e,arguments),e=r.apply(s,e),this._chain&&(e=new o(e),e._chain=n),e}})}var n=!0,r=null,i=!1,A,O,M,_,D="object"==typeof exports&&exports&&("object"==typeof global&&global&&global==global.global&&(e=global),exports),P=Array.prototype,H=Object.prototype,B=0,j=e._,F=/[-+=!~*%&^<>|{(\/]|\[\D|\b(?:delete|in|instanceof|new|typeof|void)\b/ +,I=/^';/,q=/^'\+/,R=/(?:__p\+='|\+')$/,U=/\b__p\+='';/g,z=/\b(__p\+?=)''\+/g,W=/(__w?e\(.*?\)|\b__w?t\))\+'';/g,X=/(?:__e|__t=)\(\s*(?![\d\s"']|this\.)/g,V=RegExp("^"+(H.valueOf+"").replace(/[.*+?^=!:${}()|[\]\/\\]/g,"\\$&").replace(/valueOf|for [^\]]+/g,".+?")+"$"),$=/__token__(\d+)/g,J=/[&<"']/g,K=/['\n\r\t\u2028\u2029\\]/g,Q="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" "),G="__token__",Y=[],Z=P.concat,et=H.hasOwnProperty,tt=P.push,nt=H +.propertyIsEnumerable,rt=P.slice,it=H.toString,st=V.test(st=rt.bind)&&st,ot=V.test(ot=Array.isArray)&&ot,ut=e.isFinite,at=V.test(at=Object.keys)&&at,ft="[object Array]",lt="[object Boolean]",ct="[object Date]",ht="[object Function]",pt="[object Number]",dt="[object RegExp]",vt="[object String]",mt=e.clearTimeout,gt=e.setTimeout,yt=!nt.call({valueOf:0},"valueOf"),bt="x"!=rt.call("x")[0],wt="xx"!="x"[0]+Object("x")[0],Et=st&&/\n|Opera/.test(st+it.call(e.opera)),St=at&&/^.+$|true/.test(at+!!e.attachEvent +),xt={"&":"&","<":"<",'"':""","'":"'"},Tt={"boolean":i,"function":n,object:n,number:i,string:i,"undefined":i},Nt={"\\":"\\","'":"'","\n":"n","\r":"r"," ":"t","\u2028":"u2028","\u2029":"u2029"};s.templateSettings={escape:/<%-([\s\S]+?)%>/g,evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,variable:"obj"};var Ct={a:"f,d,H",j:"f",q:"if(!d){d=k}else if(H)d=o(d,H)",i:"d(n[l],l,f)"},kt={j:"true",i:"if(!d(n[l],l,f))return!A"},Lt={a:"t",j:"t",q:"for(var D,E=1,p=arguments.length;E-1"},i:"if(n[l]===G)return true"}),Ht=u(Ct,kt),Bt=u(Ct,At),jt=u(Ct,Ot +,{j:"",i:"if(d(n[l],l,f))return n[l]"}),Ft=u(Ct,Ot),It=u(Ct,{j:"{}",q:"var v,m=typeof d=='function';if(m&&H)d=o(d,H)",i:"v=m?d(n[l],l,f):n[l][d];(j.call(A,v)?A[v]:A[v]=[]).push(n[l])"}),qt=u(_t,{a:"f,q",q:"var b=C.call(arguments,2),m=typeof q=='function'",i:{b:"A[l]=(m?q:n[l][q]).apply(n[l],b)",m:"A"+(St?"[w]=":".push")+"((m?q:n[l][q]).apply(n[l],b))"}}),Rt=u(Ct,_t),Ut=u(_t,{a:"f,y",i:{b:"A[l]=n[l][y]",m:"A"+(St?"[w]=":".push")+"(n[l][y])"}}),zt=u({a:"f,d,a,H",j:"a",q:"var s=arguments.length<3;if(H)d=o(d,H)" +,d:{b:"if(s)A=f[++l]"},i:{b:"A=d(A,n[l],l,f)",m:"A=s?(s=false,n[l]):d(A,n[l],l,f)"}}),Wt=u(Ct,At,{i:"!"+At.i}),Xt=u(Ct,kt,{j:"false",i:kt.i.replace("!","")}),Vt=u(Ct,_t,{q:"if(typeof d=='string'){var v=d;d=function(f){return f[v]}}else if(H)d=o(d,H)",i:{b:"A[l]={a:d(n[l],l,f),b:n[l]}",m:"A"+(St?"[w]=":".push")+"({a:d(n[l],l,f),b:n[l]})"},e:"A.sort(g);p=A.length;while(p--){A[p]=A[p].b}"}),$t=u(Lt,{i:"if(A[l]==null)"+Lt.i}),Jt=u(Lt),Kt=u(Ct,Ot,Mt,{r:i}),Qt=u(Ct,Ot,Mt),Gt=u({a:"t",j:"[]",r:i,i:"if(I.call(n[l])==i)A.push(l)" +,e:"A.sort()"});Ft({Arguments:"[object Arguments]",Date:ct,Function:ht,Number:pt,RegExp:dt,String:vt},function(e,t){s["is"+t]=function(t){return it.call(t)==e}}),s.isArguments(arguments)||(s.isArguments=function(e){return!!e&&!!et.call(e,"callee")});var Yt=ot||function(e){return it.call(e)==ft},Zt=u({a:"J",j:"true",q:"var e=I.call(J);if(e==c||e==F)return!J.length",i:{m:"return false"}}),en=at?function(e){return"function"==typeof e&&nt.call(e,"prototype")?Dt(e):at(e)}:Dt,tn=u({a:"t",j:"[]",i:"A.push(n[l])" +});s.VERSION="0.4.0",s.after=function(e,t){return 1>e?t():function(){if(1>--e)return t.apply(this,arguments)}},s.bind=N,s.bindAll=function(e){var t=arguments,n=1;1==t.length&&(n=0,t=Gt(e));for(var r=t.length;nw(i,e[n],r)&&t.push(e[n]);return t},s.escape=function(e){return e==r?"":(e+"").replace(J,c)},s.every=Ht,s.extend=Jt,s.filter=Bt,s.find=jt,s.first=y,s.flatten=b,s.forEach=Ft,s.forIn=Kt,s.forOwn=Qt,s.functions=Gt,s.groupBy=It,s.has=function(e,t){return et.call(e,t)},s.identity=k,s.indexOf=w,s.initial=function(e,t,n){return e?rt.call(e,0,-(t==r||n?1:t)):[]},s.intersection=function(e){var t=[];if(!e)return t;for(var n, +r=-1,i=e.length,s=rt.call(arguments,1);++rw(t,n)&&Ht(s,function(e){return-1n?Math.max(0,r+n):Math.min(n,r-1))+1);r--;)if(e[r]===t)return r;return-1},s.map=Rt,s.max=E,s.memoize=function(e,t){var n={};return function(){var r=t?t.apply(this,arguments):arguments[0];return et.call(n,r)?n[r]:n[r]=e.apply(this,arguments)}},s.min=function(e,t,n){var r=Infinity,i=r;if(!e)return i;var s=-1,o= +e.length;if(!t){for(;++s>>0?e.length:en(e).length},s.some=Xt,s.sortBy=Vt,s.sortedIndex=x,s.tap=function(e,t){return t(e),e},s.template=function(e,t,n){n||(n={});var i,o,u,a,c;i=n.escape,o=n.evaluate,u=n.interpolate;var h=s.templateSettings,n=n.variable;i==r&&(i=h.escape),o==r&&(o=h.evaluate),u==r&&(u=h.interpolate),i&&(e=e.replace(i,d)),u&&(e=e.replace(u,m)),o!=A&&(A=o,_=RegExp((o?o.source:"($^)")+"||","g")),u=Y.length,e= +e.replace(_,v),i=Y.length-1,o=u<=i,!n&&(n=h.variable||O||"obj",c=o)&&(Y[u]="';__with("+n+"){"+Y[u].replace(I,"").replace(q,"__p+="),Y[i]=Y[i].replace(R,"")+"}____p+='"),h="$&"+n+".",e="__p='"+e.replace(K,l).replace($,f)+"';",Y.length=0,c&&(u=e.indexOf("__with"),i=e.indexOf("}__",u+10)),n!=O&&(O=n,M=RegExp("([(\\s])"+n+"\\."+n+"\\b","g")),e=(c?e.slice(0,u):e).replace(X,h).replace(M,"$1__d")+(c?e.slice(u+2,i+1)+e.slice(i+3).replace(X,h).replace(M,"$1__d"):""),e=(o?e.replace(U,""):e).replace(z,"$1") +.replace(W,"$1;"),e="function("+n+"){"+n+"||("+n+"={});var __p,__t,__wt,__d="+n+"."+n+"||"+n+",__e=_.escape,__we=__e"+(o?",__j=Array.prototype.join;function print(){__p+=__j.call(arguments,'')}":";")+e+"return __p}";try{a=Function("_","return "+e)(s)}catch(p){a=function(){throw p}}return t?a(t):(a.source=e,a)},s.throttle=function(e,t){function n(){a=new Date,u=r,e.apply(o,i)}var i,s,o,u,a=0;return function(){var r=new Date,f=t-(r-a);return i=arguments,o=this,0>=f?(a=r,s=e.apply(o,i)):u||(u=gt(n,f +)),s}},s.times=function(e,t,n){var r=-1;if(n)for(;++r>>0?(bt?it.call(e)==vt:"string"==typeof e)?e.split(""):rt.call(e):tn(e)},s.union=function(){for(var e=-1,t=[],n=Z.apply(t,arguments),r=n.length;++ew(t,n[e])&&t.push(n[e]);return t},s.uniq=T,s.uniqueId=function(e){var t=B++;return e?e+t:t},s.values=tn,s.without=function(e){var t=[]; +if(!e)return t;for(var n=-1,r=e.length;++nw(arguments,e[n],1)&&t.push(e[n]);return t},s.wrap=function(e,t){return function(){var n=[e];return arguments.length&&tt.apply(n,arguments),t.apply(this,n)}},s.zip=function(e){if(!e)return[];for(var t=-1,n=E(Ut(arguments,"length")),r=Array(n);++t - + @@ -45,4 +45,4 @@ }; - \ No newline at end of file + diff --git a/perf/perf.js b/perf/perf.js index 937bf58664..20a6bf1680 100644 --- a/perf/perf.js +++ b/perf/perf.js @@ -46,6 +46,18 @@ /*--------------------------------------------------------------------------*/ + /** + * Gets the Hz, i.e. operations per second, of `bench` adjusted for the + * margin of error. + * + * @private + * @param {Object} bench The benchmark object. + * @returns {Number} Returns the adjusted Hz. + */ + function getHz(bench) { + return 1 / (bench.stats.mean + bench.stats.moe); + } + /** * Logs text to the console. * @@ -76,8 +88,11 @@ nestedNumbers = [1, [2], [3, [[4]]]], twoNumbers = [12, 21]; - var ctor = function() { }, - func = function(greeting) { return greeting + ': ' + this.name; }; + var ctor = function() { }; + + var func = function(greeting, punctuation) { + return greeting + ', ' + this.name + (punctuation || '.'); + }; var lodashBoundNormal = lodash.bind(func, { 'name': 'moe' }), lodashBoundCtor = lodash.bind(ctor, { 'name': 'moe' }), @@ -87,6 +102,94 @@ _boundCtor = _.bind(ctor, { 'name': 'moe' }), _boundPartial = _.bind(func, { 'name': 'moe' }, 'hi'); + var tplData = { + 'header1': 'Header1', + 'header2': 'Header2', + 'header3': 'Header3', + 'header4': 'Header4', + 'header5': 'Header5', + 'header6': 'Header6', + 'list': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] + }; + + var tplBase = + '
' + + "

<%= header1 %>

" + + "

<%= header2 %>

" + + "

<%= header3 %>

" + + "

<%= header4 %>

" + + "
<%= header5 %>
" + + "
<%= header6 %>
"; + + var tpl = + tplBase + + "
    " + + "
  • <%= list[0] %>
  • " + + "
  • <%= list[1] %>
  • " + + "
  • <%= list[2] %>
  • " + + "
  • <%= list[3] %>
  • " + + "
  • <%= list[4] %>
  • " + + "
  • <%= list[5] %>
  • " + + "
  • <%= list[6] %>
  • " + + "
  • <%= list[7] %>
  • " + + "
  • <%= list[8] %>
  • " + + "
  • <%= list[9] %>
  • " + + '
' + + '
'; + + var tplWithEvaluate = + tplBase + + "
    " + + '<% for (var index = 0, length = list.length; index < length; index++) { %>' + + "
  • <%= list[index] %>
  • " + + '<% } %>' + + '
' + + ''; + + var tplBaseVerbose = + '
' + + "

<%= data.header1 %>

" + + "

<%= data.header2 %>

" + + "

<%= data.header3 %>

" + + "

<%= data.header4 %>

" + + "
<%= data.header5 %>
" + + "
<%= data.header6 %>
"; + + var tplVerbose = + tplBaseVerbose + + "
    " + + "
  • <%= data.list[0] %>
  • " + + "
  • <%= data.list[1] %>
  • " + + "
  • <%= data.list[2] %>
  • " + + "
  • <%= data.list[3] %>
  • " + + "
  • <%= data.list[4] %>
  • " + + "
  • <%= data.list[5] %>
  • " + + "
  • <%= data.list[6] %>
  • " + + "
  • <%= data.list[7] %>
  • " + + "
  • <%= data.list[8] %>
  • " + + "
  • <%= data.list[9] %>
  • " + + '
' + + '
'; + + var tplVerboseWithEvaluate = + tplBaseVerbose + + "
    " + + '<% for (var index = 0, length = data.list.length; index < length; index++) { %>' + + "
  • <%= data.list[index] %>
  • " + + '<% } %>' + + '
' + + ''; + + var lodashTpl = lodash.template(tpl), + lodashTplWithEvaluate = lodash.template(tplWithEvaluate), + lodashTplVerbose = lodash.template(tplVerbose, null, { 'variable': 'data' }), + lodashTplVerboseWithEvaluate = lodash.template(tplVerboseWithEvaluate, null, { 'variable': 'data' }); + + var _tpl = _.template(tpl), + _tplWithEvaluate = _.template(tplWithEvaluate), + _tplVerbose = _.template(tplVerbose, null, { 'variable': 'data' }), + _tplVerboseWithEvaluate = _.template(tplVerboseWithEvaluate, null, { 'variable': 'data' }); + var wordToNumber = { 'one': 1, 'two': 2, @@ -138,20 +241,24 @@ 'onComplete': function() { var formatNumber = Benchmark.formatNumber, fastest = this.filter('fastest'), + fastestHz = getHz(fastest[0]), slowest = this.filter('slowest'), - lodashHz = 1 / (this[0].stats.mean + this[0].stats.moe), - underscoreHz = 1 / (this[1].stats.mean + this[1].stats.moe); + slowestHz = getHz(slowest[0]), + lodashHz = getHz(this[0]), + underscoreHz = getHz(this[1]); if (fastest.length > 1) { log('It\'s too close to call.'); - lodashHz = underscoreHz = Math.min(lodashHz, underscoreHz); + lodashHz = underscoreHz = slowestHz; } else { - var fastestHz = fastest[0] == this[0] ? lodashHz : underscoreHz, - slowestHz = slowest[0] == this[0] ? lodashHz : underscoreHz, - percent = ((fastestHz / slowestHz) - 1) * 100; + var percent = ((fastestHz / slowestHz) - 1) * 100; - log(fastest[0].name + ' is ' + formatNumber(percent < 1 ? percent.toFixed(2) : Math.round(percent)) + '% faster.'); + log( + fastest[0].name + ' is ' + + formatNumber(percent < 1 ? percent.toFixed(2) : Math.round(percent)) + + '% faster.' + ); } // add score adjusted for margin of error score.lodash += lodashHz; @@ -184,7 +291,7 @@ /*--------------------------------------------------------------------------*/ suites.push( - Benchmark.Suite('bind call') + Benchmark.Suite('`_.bind` (uses native `Function#bind` if available and inferred fast)') .add('Lo-Dash', function() { lodash.bind(func, { 'name': 'moe' }, 'hi'); }) @@ -194,7 +301,7 @@ ); suites.push( - Benchmark.Suite('bound') + Benchmark.Suite('bound call') .add('Lo-Dash', function() { lodashBoundNormal(); }) @@ -204,7 +311,17 @@ ); suites.push( - Benchmark.Suite('bound partial') + Benchmark.Suite('bound call with arguments') + .add('Lo-Dash', function() { + lodashBoundNormal('hi', '!'); + }) + .add('Underscore', function() { + _boundNormal('hi', '!'); + }) + ); + + suites.push( + Benchmark.Suite('bound and partially applied call (uses native `Function#bind` if available)') .add('Lo-Dash', function() { lodashBoundPartial(); }) @@ -214,7 +331,17 @@ ); suites.push( - Benchmark.Suite('bound constructor') + Benchmark.Suite('bound and partially applied call with arguments (uses native `Function#bind` if available)') + .add('Lo-Dash', function() { + lodashBoundPartial('!'); + }) + .add('Underscore', function() { + _boundPartial('!'); + }) + ); + + suites.push( + Benchmark.Suite('bound and called in a `new` expression, i.e. `new bound` (edge case)') .add('Lo-Dash', function() { new lodashBoundCtor(); }) @@ -226,19 +353,23 @@ /*--------------------------------------------------------------------------*/ suites.push( - Benchmark.Suite('each array') + Benchmark.Suite('`_.each` iterating an array') .add('Lo-Dash', function() { var result = []; - lodash.each(numbers, function(num) { result.push(num * 2); }); + lodash.each(numbers, function(num) { + result.push(num * 2); + }); }) .add('Underscore', function() { var result = []; - _.each(numbers, function(num) { result.push(num * 2); }); + _.each(numbers, function(num) { + result.push(num * 2); + }); }) ); suites.push( - Benchmark.Suite('each array thisArg (slow path)') + Benchmark.Suite('`_.each` iterating an array with `thisArg` (slow path)') .add('Lo-Dash', function() { var result = []; lodash.each(numbers, function(num, index) { @@ -254,7 +385,7 @@ ); suites.push( - Benchmark.Suite('each object') + Benchmark.Suite('`_.each` iterating an object') .add('Lo-Dash', function() { var result = []; lodash.each(object, function(num) { @@ -272,7 +403,51 @@ /*--------------------------------------------------------------------------*/ suites.push( - Benchmark.Suite('find') + Benchmark.Suite('`_.filter` iterating an array') + .add('Lo-Dash', function() { + lodash.filter(numbers, function(num) { + return num % 2; + }); + }) + .add('Underscore', function() { + _.filter(numbers, function(num) { + return num % 2; + }); + }) + ); + + suites.push( + Benchmark.Suite('`_.filter` iterating an array with `thisArg` (slow path)') + .add('Lo-Dash', function() { + lodash.filter(numbers, function(num, index) { + return this['key' + index] % 2; + }, object); + }) + .add('Underscore', function() { + _.filter(numbers, function(num, index) { + return this['key' + index] % 2; + }, object); + }) + ); + + suites.push( + Benchmark.Suite('`_.filter` iterating an object') + .add('Lo-Dash', function() { + lodash.filter(object, function(num) { + return num % 2; + }); + }) + .add('Underscore', function() { + _.filter(object, function(num) { + return num % 2; + }); + }) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.find` iterating an array') .add('Lo-Dash', function() { lodash.find(numbers, function(num) { return num === 19; @@ -285,10 +460,24 @@ }) ); + suites.push( + Benchmark.Suite('`_.find` iterating an object') + .add('Lo-Dash', function() { + lodash.find(numbers, function(value, key) { + return /\D9$/.test(key); + }); + }) + .add('Underscore', function() { + _.find(numbers, function(value, key) { + return /\D9$/.test(key); + }); + }) + ); + /*--------------------------------------------------------------------------*/ suites.push( - Benchmark.Suite('flatten deep') + Benchmark.Suite('`_.flatten`') .add('Lo-Dash', function() { lodash.flatten(nestedNumbers); }) @@ -298,7 +487,7 @@ ); suites.push( - Benchmark.Suite('flatten shallow') + Benchmark.Suite('`_.flatten` with `shallow`') .add('Lo-Dash', function() { lodash.flatten(nestedNumbers, true); }) @@ -310,19 +499,19 @@ /*--------------------------------------------------------------------------*/ suites.push( - Benchmark.Suite('difference') + Benchmark.Suite('`_.difference`') .add('Lo-Dash', function() { - lodash.difference(numbers, fourNumbers); + lodash.difference(numbers, fourNumbers, twoNumbers); }) .add('Underscore', function() { - _.difference(numbers, fourNumbers); + _.difference(numbers, fourNumbers, twoNumbers); }) ); /*--------------------------------------------------------------------------*/ suites.push( - Benchmark.Suite('groupBy callback') + Benchmark.Suite('`_.groupBy` with `callback` iterating an array') .add('Lo-Dash', function() { lodash.groupBy(numbers, function(num) { return num >> 1; }); }) @@ -332,7 +521,7 @@ ); suites.push( - Benchmark.Suite('groupBy property name') + Benchmark.Suite('`_.groupBy` with `property` name iterating an array') .add('Lo-Dash', function() { lodash.groupBy(words, 'length'); }) @@ -341,10 +530,20 @@ }) ); + suites.push( + Benchmark.Suite('`_.groupBy` with `callback` iterating an object') + .add('Lo-Dash', function() { + lodash.groupBy(wordToNumber, function(num) { return num >> 1; }); + }) + .add('Underscore', function() { + _.groupBy(wordToNumber, function(num) { return num >> 1; }); + }) + ); + /*--------------------------------------------------------------------------*/ suites.push( - Benchmark.Suite('indexOf') + Benchmark.Suite('`_.indexOf`') .add('Lo-Dash', function() { lodash.indexOf(numbers, 9); }) @@ -354,7 +553,7 @@ ); suites.push( - Benchmark.Suite('indexOf isSorted') + Benchmark.Suite('`_.indexOf` with `isSorted`') .add('Lo-Dash', function() { lodash.indexOf(numbers, 19, true); }) @@ -366,7 +565,7 @@ /*--------------------------------------------------------------------------*/ suites.push( - Benchmark.Suite('intersection') + Benchmark.Suite('`_.intersection`') .add('Lo-Dash', function() { lodash.intersection(numbers, fourNumbers, twoNumbers); }) @@ -378,7 +577,7 @@ /*--------------------------------------------------------------------------*/ suites.push( - Benchmark.Suite('keys') + Benchmark.Suite('`_.keys` (uses native `Object.keys` if available)') .add('Lo-Dash', function() { lodash.keys(object); }) @@ -390,7 +589,7 @@ /*--------------------------------------------------------------------------*/ suites.push( - Benchmark.Suite('lastIndexOf') + Benchmark.Suite('`_.lastIndexOf`') .add('Lo-Dash', function() { lodash.lastIndexOf(numbers, 9); }) @@ -402,7 +601,7 @@ /*--------------------------------------------------------------------------*/ suites.push( - Benchmark.Suite('map') + Benchmark.Suite('`_.map` iterating an array') .add('Lo-Dash', function() { lodash.map(objects, function(value) { return value.num; @@ -416,7 +615,7 @@ ); suites.push( - Benchmark.Suite('map thisArg (slow path)') + Benchmark.Suite('`_.map` with `thisArg` iterating an array (slow path)') .add('Lo-Dash', function() { lodash.map(objects, function(value, index) { return this['key' + index] + value.num; @@ -429,10 +628,24 @@ }) ); + suites.push( + Benchmark.Suite('`_.map` iterating an object') + .add('Lo-Dash', function() { + lodash.map(object, function(value) { + return value; + }); + }) + .add('Underscore', function() { + _.map(object, function(value) { + return value; + }); + }) + ); + /*--------------------------------------------------------------------------*/ suites.push( - Benchmark.Suite('max') + Benchmark.Suite('`_.max`') .add('Lo-Dash', function() { lodash.max(numbers); }) @@ -444,7 +657,7 @@ /*--------------------------------------------------------------------------*/ suites.push( - Benchmark.Suite('min') + Benchmark.Suite('`_.min`') .add('Lo-Dash', function() { lodash.min(numbers); }) @@ -456,7 +669,7 @@ /*--------------------------------------------------------------------------*/ suites.push( - Benchmark.Suite('pick') + Benchmark.Suite('`_.pick`') .add('Lo-Dash', function() { lodash.pick(object, 'key6', 'key13'); }) @@ -468,7 +681,7 @@ /*--------------------------------------------------------------------------*/ suites.push( - Benchmark.Suite('pluck') + Benchmark.Suite('`_.pluck`') .add('Lo-Dash', function() { lodash.pluck(objects, 'num'); }) @@ -480,7 +693,7 @@ /*--------------------------------------------------------------------------*/ suites.push( - Benchmark.Suite('shuffle') + Benchmark.Suite('`_.shuffle`') .add('Lo-Dash', function() { lodash.shuffle(numbers); }) @@ -492,7 +705,29 @@ /*--------------------------------------------------------------------------*/ suites.push( - Benchmark.Suite('sortBy callback') + Benchmark.Suite('`_.size` with an array') + .add('Lo-Dash', function() { + lodash.size(numbers); + }) + .add('Underscore', function() { + _.size(numbers); + }) + ); + + suites.push( + Benchmark.Suite('`_.size` with an object') + .add('Lo-Dash', function() { + lodash.size(object); + }) + .add('Underscore', function() { + _.size(object); + }) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.sortBy` with `callback`') .add('Lo-Dash', function() { lodash.sortBy(numbers, function(num) { return Math.sin(num); }); }) @@ -502,7 +737,7 @@ ); suites.push( - Benchmark.Suite('sortBy callback thisArg (slow path)') + Benchmark.Suite('`_.sortBy` with `callback` and `thisArg` (slow path)') .add('Lo-Dash', function() { lodash.sortBy(numbers, function(num) { return this.sin(num); }, Math); }) @@ -512,7 +747,7 @@ ); suites.push( - Benchmark.Suite('sortBy property name') + Benchmark.Suite('`_.sortBy` with `property` name') .add('Lo-Dash', function() { lodash.sortBy(words, 'length'); }) @@ -524,7 +759,7 @@ /*--------------------------------------------------------------------------*/ suites.push( - Benchmark.Suite('sortedIndex') + Benchmark.Suite('`_.sortedIndex`') .add('Lo-Dash', function() { lodash.sortedIndex(numbers, 25); }) @@ -534,7 +769,7 @@ ); suites.push( - Benchmark.Suite('sortedIndex callback') + Benchmark.Suite('`_.sortedIndex` with `callback`') .add('Lo-Dash', function() { lodash.sortedIndex(words, 'twenty-five', function(value) { return wordToNumber[value]; @@ -550,7 +785,69 @@ /*--------------------------------------------------------------------------*/ suites.push( - Benchmark.Suite('times') + Benchmark.Suite('`_.template` without "evaluate" delimiters (slow path)') + .add('Lo-Dash', function() { + lodash.template(tpl, tplData); + }) + .add('Underscore', function() { + _.template(tpl, tplData); + }) + ); + + suites.push( + Benchmark.Suite('`_.template` with "evaluate" delimiters (slow path)') + .add('Lo-Dash', function() { + lodash.template(tplWithEvaluate, tplData); + }) + .add('Underscore', function() { + _.template(tplWithEvaluate, tplData); + }) + ); + + suites.push( + Benchmark.Suite('compiled template without "evaluate" delimiters') + .add('Lo-Dash', function() { + lodashTpl(tplData); + }) + .add('Underscore', function() { + _tpl(tplData); + }) + ); + + suites.push( + Benchmark.Suite('compiled template with "evaluate" delimiters') + .add('Lo-Dash', function() { + lodashTplWithEvaluate(tplData); + }) + .add('Underscore', function() { + _tplWithEvaluate(tplData); + }) + ); + + suites.push( + Benchmark.Suite('compiled template without a with-statement or "evaluate" delimiters') + .add('Lo-Dash', function() { + lodashTplVerbose(tplData); + }) + .add('Underscore', function() { + _tplVerbose(tplData); + }) + ); + + suites.push( + Benchmark.Suite('compiled template without a with-statement using "evaluate" delimiters') + .add('Lo-Dash', function() { + lodashTplVerboseWithEvaluate(tplData); + }) + .add('Underscore', function() { + _tplVerboseWithEvaluate(tplData); + }) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.times`') .add('Lo-Dash', function() { var result = []; lodash.times(length, function(n) { result.push(n); }); @@ -562,7 +859,7 @@ ); suites.push( - Benchmark.Suite('times thisArg') + Benchmark.Suite('`_.times` with `thisArg`') .add('Lo-Dash', function() { var result = []; lodash.times(length, function(n) { result.push(this.sin(n)); }, Math); @@ -576,7 +873,29 @@ /*--------------------------------------------------------------------------*/ suites.push( - Benchmark.Suite('union') + Benchmark.Suite('`_.toArray` with an array') + .add('Lo-Dash', function() { + lodash.toArray(numbers); + }) + .add('Underscore', function() { + _.toArray(numbers); + }) + ); + + suites.push( + Benchmark.Suite('`_.toArray` with an object') + .add('Lo-Dash', function() { + lodash.toArray(object); + }) + .add('Underscore', function() { + _.toArray(object); + }) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.union`') .add('Lo-Dash', function() { lodash.union(numbers, fourNumbers, twoNumbers); }) @@ -588,7 +907,7 @@ /*--------------------------------------------------------------------------*/ suites.push( - Benchmark.Suite('uniq') + Benchmark.Suite('`_.uniq`') .add('Lo-Dash', function() { lodash.uniq(numbers.concat(fourNumbers, twoNumbers)); }) @@ -598,7 +917,7 @@ ); suites.push( - Benchmark.Suite('uniq callback') + Benchmark.Suite('`_.uniq` with `callback`') .add('Lo-Dash', function() { lodash.uniq(numbers.concat(fourNumbers, twoNumbers), function(num) { return num % 2; @@ -614,7 +933,7 @@ /*--------------------------------------------------------------------------*/ suites.push( - Benchmark.Suite('values') + Benchmark.Suite('`_.values`') .add('Lo-Dash', function() { lodash.values(object); }) diff --git a/test/backbone.html b/test/backbone.html index 59e45781bb..1ea36e70cc 100644 --- a/test/backbone.html +++ b/test/backbone.html @@ -25,7 +25,10 @@

Test

- + + @@ -35,4 +38,4 @@

Test

- \ No newline at end of file + diff --git a/test/index.html b/test/index.html index 6574537380..a5c378be36 100644 --- a/test/index.html +++ b/test/index.html @@ -8,46 +8,57 @@
+ - - - - \ No newline at end of file + diff --git a/test/run-test.sh b/test/run-test.sh index 0276f4ea93..43424e4378 100755 --- a/test/run-test.sh +++ b/test/run-test.sh @@ -6,4 +6,4 @@ for cmd in rhino ringo narwhal node; do done echo "" echo "Testing in a browser..." -open index.html \ No newline at end of file +open index.html diff --git a/test/test-ui.js b/test/test-ui.js new file mode 100644 index 0000000000..74409a9134 --- /dev/null +++ b/test/test-ui.js @@ -0,0 +1,90 @@ +;(function(window) { + 'use strict'; + + /** `QUnit.addEvent` shortcut */ + var addEvent = QUnit.addEvent; + + /** The Lo-Dash build to load */ + var build = (/build=([^&]+)/.exec(location.search) || [])[1]; + + /** A flag to determine if RequireJS should be loaded */ + var norequire = /[?&]norequire=true(?:&|$)/.test(location.search); + + /*--------------------------------------------------------------------------*/ + + // assign `QUnit.config` properties + QUnit.config.lodashFilename = (function() { + switch (build) { + case 'prod': return 'lodash.min'; + case 'custom': return 'lodash.custom.min'; + case 'custom-debug': return 'lodash.custom'; + } + return 'lodash'; + }()); + + // assign `QUnit.urlParams` properties + QUnit.extend(QUnit.urlParams, { + 'build': build, + 'norequire': norequire + }); + + // initialize the build dropdown + addEvent(window, 'load', function() { + function eventHandler(event) { + var search = location.search.replace(/^\?|&?(?:build|norequire)=[^&]*&?/g, ''); + if (event.stopPropagation) { + event.stopPropagation(); + } else { + event.cancelBubble = true; + } + location.href = + location.href.split('?')[0] + '?' + + (search ? search + '&' : '') + 'build=' + + dropdown[dropdown.selectedIndex].value + + (checkbox.checked ? '&norequire=true' : ''); + } + + function init() { + var header = document.getElementById('qunit-header'); + if (header) { + header.appendChild(label1); + header.appendChild(label2); + + dropdown.selectedIndex = (function() { + switch (build) { + case 'prod': return 1; + case 'custom': return 2; + case 'custom-debug': return 3; + } + return 0; + }()); + + checkbox.checked = norequire; + addEvent(checkbox, 'click', eventHandler); + addEvent(dropdown, 'change', eventHandler); + } + else { + setTimeout(init, 15); + } + } + + var label1 = document.createElement('label'); + label1.innerHTML = + 'norequire'; + + var label2 = document.createElement('label'); + label2.innerHTML = + 'build'; + + var checkbox = label1.firstChild, + dropdown = label2.firstChild; + + init(); + }); + +}(this)); diff --git a/test/test.js b/test/test.js index f879363bc7..e6bed5281f 100644 --- a/test/test.js +++ b/test/test.js @@ -1,4 +1,5 @@ -(function(window, undefined) { +;(function(window, undefined) { + 'use strict'; /** Use a single load function */ var load = typeof require == 'function' ? require : window.load; @@ -23,9 +24,6 @@ /** Shortcut used to convert array-like objects to arrays */ var slice = [].slice; - /** Used to resolve a value's internal [[Class]] */ - var toString = {}.toString; - /** Used to check problem JScript properties (a.k.a. the [[DontEnum]] bug) */ var shadowed = { 'constructor': 1, @@ -71,7 +69,7 @@ (function() { test('supports loading lodash.js as the "lodash" module', function() { if (window.document && window.require) { - equal((_2 || {}).moduleName, 'lodash'); + equal((lodashModule || {}).moduleName, 'lodash'); } else { skipTest(1) } @@ -79,15 +77,15 @@ test('supports loading lodash.js as the "underscore" module', function() { if (window.document && window.require) { - equal((_3 || {}).moduleName, 'underscore'); + equal((underscoreModule || {}).moduleName, 'underscore'); } else { skipTest(1) } }); test('avoids overwritten native methods', function() { - if (window.lodashBadKeys) { - notDeepEqual(lodashBadKeys.keys({ 'a': 1 }), []); + if (window.document) { + notDeepEqual(lodashBadShim.keys({ 'a': 1 }), []); } else { skipTest(1); } @@ -134,6 +132,23 @@ /*--------------------------------------------------------------------------*/ + QUnit.module('lodash.contains'); + + (function() { + _.each([ + { 'kind': 'literal', 'value': 'abc' }, + { 'kind': 'object', 'value': Object('abc') } + ], + function(data) { + test('should work with a string ' + data.kind + ' for `collection`', function() { + equal(_.contains(data.value, 'bc'), true); + equal(_.contains(data.value, 'd'), false); + }); + }); + }()); + + /*--------------------------------------------------------------------------*/ + QUnit.module('lodash.debounce'); (function() { @@ -246,6 +261,26 @@ _.forEach(object, function(value, key) { keys.push(key); }); deepEqual(keys, ['length']); }); + + _.each([ + { 'kind': 'literal', 'value': 'abc' }, + { 'kind': 'object', 'value': Object('abc') } + ], + function(data) { + test('should work with a string ' + data.kind + ' for `collection` (test in IE < 9)', function() { + var args, + collection = data.value, + values = []; + + _.forEach(collection, function(value) { + args || (args = slice.call(arguments)); + values.push(value); + }); + + deepEqual(args, ['a', 0, collection]); + deepEqual(values, ['a', 'b', 'c']); + }); + }); }()); /*--------------------------------------------------------------------------*/ @@ -327,6 +362,14 @@ deepEqual(actual.constructor, [1.3]); deepEqual(actual.hasOwnProperty, [2.1, 2.4]); }); + + test('should work with an object for `collection`', function() { + var actual = _.groupBy({ 'a': 1.3, 'b': 2.1, 'c': 2.4 }, function(num) { + return Math.floor(num); + }); + + deepEqual(actual, { '1': [1.3], '2': [2.1, 2.4] }); + }); }()); /*--------------------------------------------------------------------------*/ @@ -547,25 +590,53 @@ (function() { test('should pass the correct `callback` arguments when iterating an object', function() { var args, - object = { 'a': 'A', 'b': 'B', 'c': 'C' }, - keys = _.keys(object); + object = { 'a': 'A', 'b': 'B' }, + lastKey = _.keys(object).pop(); + + var expected = lastKey == 'a' + ? ['A', 'B', 'b', object] + : ['B', 'A', 'a', object]; _.reduceRight(object, function() { args || (args = slice.call(arguments)); }); - deepEqual(args, ['C', 'B', 'b', object]); + deepEqual(args, expected); }); test('should treat array-like object with invalid `length` as a regular object', function() { var args, - object = { 'a': 'A', 'length': -1 }; + object = { 'a': 'A', 'length': -1 }, + lastKey = _.keys(object).pop(); + + var expected = lastKey == 'a' + ? ['A', '-1', 'length', object] + : [-1, 'A', 'a', object]; _.reduceRight(object, function() { args || (args = slice.call(arguments)); }); - deepEqual(args, [-1, 'A', 'a', object]); + deepEqual(args, expected); + }); + + _.each([ + { 'kind': 'literal', 'value': 'abc' }, + { 'kind': 'object', 'value': Object('abc') } + ], + function(data) { + test('should work with a string ' + data.kind + ' for `collection` (test in IE < 9)', function() { + var args, + collection = data.value; + + var actual = _.reduceRight(collection, function(accumulator, value) { + args || (args = slice.call(arguments)); + return accumulator + value; + }); + + deepEqual(args, ['c', 'b', 1, collection]); + equal(actual, 'cba'); + }); }); }()); @@ -574,14 +645,29 @@ QUnit.module('lodash.size'); (function() { + var args = arguments; + test('should detect the size of a string value', function() { equal(_.size('abc'), 3); }); + test('should allow a falsey `object` argument', function() { + var func = _.size; + try { + var actual = [func(), func(undefined), func(null), func(false), func(0)]; + } catch(e) { } + + deepEqual(actual, [0, 0, 0, 0, 0]); + }); + + test('should work with `arguments` objects (test in IE < 9)', function() { + equal(_.size(args), 3); + }); + test('fixes the JScript [[DontEnum]] bug (test in IE < 9)', function() { equal(_.size(shadowed), 7); }); - }()); + }(1, 2, 3)); /*--------------------------------------------------------------------------*/ @@ -595,6 +681,14 @@ deepEqual(actual, [3, 1, 2]); }); + + test('should work with an object for `collection`', function() { + var actual = _.sortBy({ 'a': 1, 'b': 2, 'c': 3 }, function(num) { + return Math.sin(num); + }); + + deepEqual(actual, [3, 1, 2]); + }); }()); /*--------------------------------------------------------------------------*/ @@ -639,6 +733,47 @@ _.template('', null, options); deepEqual(options, {}); }); + + test('should be debuggable if compiled with errors', function() { + var source = _.template('<% if x %>').source; + ok(source.indexOf('__p') > -1); + }); + + test('should raise an error if a template, compiled with errors, is executed', function() { + raises(_.template('<% if x %>')); + }); + + test('should work with complex "interpolate" delimiters', function() { + _.each({ + '<%= a + b %>': '3', + '<%= b - a %>': '1', + '<%= a = b %>': '2', + '<%= !a %>': 'false', + '<%= ~a %>': '-2', + '<%= a * b %>': '2', + '<%= a / b %>': '0.5', + '<%= a % b %>': '1', + '<%= a >> b %>': '0', + '<%= a << b %>': '4', + '<%= a & b %>': '0', + '<%= a ^ b %>': '3', + '<%= a | b %>': '3', + '<%= {}.toString.call(0) %>': '[object Number]', + '<%= a.toFixed(2) %>': '1.00', + '<%= obj["a"] %>': '1', + '<%= delete a %>': 'true', + '<%= "a" in obj %>': 'true', + '<%= obj instanceof Object %>': 'true', + '<%= new Boolean %>': 'false', + '<%= typeof a %>': 'number', + '<%= void a %>': '' + }, function(value, key) { + var compiled = _.template(key), + data = { 'a': 1, 'b': 2 }; + + equal(compiled(data), value); + }); + }); }()); /*--------------------------------------------------------------------------*/ @@ -706,6 +841,11 @@ var object = { 'length': -1 }; deepEqual(_.toArray(object), [-1]); }); + + test('should work with a string for `collection` (test in IE < 9)', function() { + deepEqual(_.toArray('abc'), ['a', 'b', 'c']); + deepEqual(_.toArray(Object('abc')), ['a', 'b', 'c']); + }); }(1, 2, 3)); /*--------------------------------------------------------------------------*/ @@ -724,6 +864,16 @@ /*--------------------------------------------------------------------------*/ + QUnit.module('lodash.zipObject'); + + (function() { + test('supports not passing a `values` argument', function() { + deepEqual(_.zipObject(['a', 'b', 'c']), { 'a': undefined, 'b': undefined, 'c': undefined }); + }); + }()); + + /*--------------------------------------------------------------------------*/ + QUnit.module('lodash(...).shift'); (function() { @@ -777,11 +927,18 @@ 'union', 'uniq', 'without', - 'zip' + 'zip', + 'zipObject' ], function(methodName) { - var pass = true; + var func = _[methodName], + pass = true; + try { - _[methodName](); + func(); + func(undefined); + func(null); + func(false); + func(0); } catch(e) { pass = false; } @@ -811,12 +968,23 @@ 'some', 'toArray' ], function(methodName) { - var pass = true; + var func = _[methodName], + identity = _.identity, + pass = true; + try { if (/^(?:contains|toArray)$/.test(methodName)) { - _[methodName](null); - } else { - _[methodName](null, _.identity); + func(); + func(undefined); + func(null); + func(false); + func(0); + } + else { + func(undefined, identity); + func(null, identity); + func(false, identity); + func(0, identity); } } catch(e) { pass = false; diff --git a/test/underscore.html b/test/underscore.html index 09a4209ead..00a6a4557c 100644 --- a/test/underscore.html +++ b/test/underscore.html @@ -22,7 +22,10 @@ - + + @@ -36,4 +39,4 @@
  • <%= data %>
  • - \ No newline at end of file + diff --git a/vendor/backbone b/vendor/backbone deleted file mode 160000 index d4d7fb97a5..0000000000 --- a/vendor/backbone +++ /dev/null @@ -1 +0,0 @@ -Subproject commit d4d7fb97a5e0392578481212f93c371470e70898 diff --git a/vendor/backbone/LICENSE b/vendor/backbone/LICENSE new file mode 100644 index 0000000000..f79bb00587 --- /dev/null +++ b/vendor/backbone/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2010-2012 Jeremy Ashkenas, DocumentCloud + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/vendor/backbone/README.md b/vendor/backbone/README.md new file mode 100644 index 0000000000..75aa0780ca --- /dev/null +++ b/vendor/backbone/README.md @@ -0,0 +1,26 @@ + ____ __ __ + /\ _`\ /\ \ /\ \ __ + \ \ \ \ \ __ ___\ \ \/'\\ \ \____ ___ ___ __ /\_\ ____ + \ \ _ <' /'__`\ /'___\ \ , < \ \ '__`\ / __`\ /' _ `\ /'__`\ \/\ \ /',__\ + \ \ \ \ \/\ \ \.\_/\ \__/\ \ \\`\\ \ \ \ \/\ \ \ \/\ \/\ \/\ __/ __ \ \ \/\__, `\ + \ \____/\ \__/.\_\ \____\\ \_\ \_\ \_,__/\ \____/\ \_\ \_\ \____\/\_\_\ \ \/\____/ + \/___/ \/__/\/_/\/____/ \/_/\/_/\/___/ \/___/ \/_/\/_/\/____/\/_/\ \_\ \/___/ + \ \____/ + \/___/ + (_'_______________________________________________________________________________'_) + (_.———————————————————————————————————————————————————————————————————————————————._) + + +Backbone supplies structure to JavaScript-heavy applications by providing models key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing application over a RESTful JSON interface. + +For Docs, License, Tests, pre-packed downloads, and everything else, really, see: +http://backbonejs.org + +To suggest a feature, report a bug, or general discussion: +http://github.com/documentcloud/backbone/issues/ + +All contributors are listed here: +http://github.com/documentcloud/backbone/contributors + +Special thanks to Robert Kieffer for the original philosophy behind Backbone. +http://github.com/broofa diff --git a/vendor/backbone/backbone.js b/vendor/backbone/backbone.js new file mode 100644 index 0000000000..15a74d10e6 --- /dev/null +++ b/vendor/backbone/backbone.js @@ -0,0 +1,1461 @@ +// Backbone.js 0.9.2 + +// (c) 2010-2012 Jeremy Ashkenas, DocumentCloud Inc. +// Backbone may be freely distributed under the MIT license. +// For all details and documentation: +// http://backbonejs.org + +(function(){ + + // Initial Setup + // ------------- + + // Save a reference to the global object (`window` in the browser, `global` + // on the server). + var root = this; + + // Save the previous value of the `Backbone` variable, so that it can be + // restored later on, if `noConflict` is used. + var previousBackbone = root.Backbone; + + // Create a local reference to splice. + var splice = Array.prototype.splice; + + // The top-level namespace. All public Backbone classes and modules will + // be attached to this. Exported for both CommonJS and the browser. + var Backbone; + if (typeof exports !== 'undefined') { + Backbone = exports; + } else { + Backbone = root.Backbone = {}; + } + + // Current version of the library. Keep in sync with `package.json`. + Backbone.VERSION = '0.9.2'; + + // Require Underscore, if we're on the server, and it's not already present. + var _ = root._; + if (!_ && (typeof require !== 'undefined')) _ = require('underscore'); + + // For Backbone's purposes, jQuery, Zepto, or Ender owns the `$` variable. + Backbone.$ = root.jQuery || root.Zepto || root.ender; + + // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable + // to its previous owner. Returns a reference to this Backbone object. + Backbone.noConflict = function() { + root.Backbone = previousBackbone; + return this; + }; + + // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option + // will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and + // set a `X-Http-Method-Override` header. + Backbone.emulateHTTP = false; + + // Turn on `emulateJSON` to support legacy servers that can't deal with direct + // `application/json` requests ... will encode the body as + // `application/x-www-form-urlencoded` instead and will send the model in a + // form param named `model`. + Backbone.emulateJSON = false; + + // Backbone.Events + // ----------------- + + // Regular expression used to split event strings + var eventSplitter = /\s+/; + + // A module that can be mixed in to *any object* in order to provide it with + // custom events. You may bind with `on` or remove with `off` callback functions + // to an event; `trigger`-ing an event fires all callbacks in succession. + // + // var object = {}; + // _.extend(object, Backbone.Events); + // object.on('expand', function(){ alert('expanded'); }); + // object.trigger('expand'); + // + var Events = Backbone.Events = { + + // Bind one or more space separated events, `events`, to a `callback` + // function. Passing `"all"` will bind the callback to all events fired. + on: function(events, callback, context) { + var calls, event, list; + if (!callback) return this; + + events = events.split(eventSplitter); + calls = this._callbacks || (this._callbacks = {}); + + while (event = events.shift()) { + list = calls[event] || (calls[event] = []); + list.push(callback, context); + } + + return this; + }, + + // Remove one or many callbacks. If `context` is null, removes all callbacks + // with that function. If `callback` is null, removes all callbacks for the + // event. If `events` is null, removes all bound callbacks for all events. + off: function(events, callback, context) { + var event, calls, list, i; + + // No events, or removing *all* events. + if (!(calls = this._callbacks)) return this; + if (!(events || callback || context)) { + delete this._callbacks; + return this; + } + + events = events ? events.split(eventSplitter) : _.keys(calls); + + // Loop through the callback list, splicing where appropriate. + while (event = events.shift()) { + if (!(list = calls[event]) || !(callback || context)) { + delete calls[event]; + continue; + } + + for (i = list.length - 2; i >= 0; i -= 2) { + if (!(callback && list[i] !== callback || context && list[i + 1] !== context)) { + list.splice(i, 2); + } + } + } + + return this; + }, + + // Trigger one or many events, firing all bound callbacks. Callbacks are + // passed the same arguments as `trigger` is, apart from the event name + // (unless you're listening on `"all"`, which will cause your callback to + // receive the true name of the event as the first argument). + trigger: function(events) { + var event, calls, list, i, length, args, all, rest; + if (!(calls = this._callbacks)) return this; + + rest = []; + events = events.split(eventSplitter); + for (i = 1, length = arguments.length; i < length; i++) { + rest[i - 1] = arguments[i]; + } + + // For each event, walk through the list of callbacks twice, first to + // trigger the event, then to trigger any `"all"` callbacks. + while (event = events.shift()) { + // Copy callback lists to prevent modification. + if (all = calls.all) all = all.slice(); + if (list = calls[event]) list = list.slice(); + + // Execute event callbacks. + if (list) { + for (i = 0, length = list.length; i < length; i += 2) { + list[i].apply(list[i + 1] || this, rest); + } + } + + // Execute "all" callbacks. + if (all) { + args = [event].concat(rest); + for (i = 0, length = all.length; i < length; i += 2) { + all[i].apply(all[i + 1] || this, args); + } + } + } + + return this; + } + + }; + + // Aliases for backwards compatibility. + Events.bind = Events.on; + Events.unbind = Events.off; + + // Backbone.Model + // -------------- + + // Create a new model, with defined attributes. A client id (`cid`) + // is automatically generated and assigned for you. + var Model = Backbone.Model = function(attributes, options) { + var defaults; + attributes || (attributes = {}); + if (options && options.collection) this.collection = options.collection; + if (options && options.parse) attributes = this.parse(attributes); + if (defaults = getValue(this, 'defaults')) { + attributes = _.extend({}, defaults, attributes); + } + this.attributes = {}; + this._escapedAttributes = {}; + this.cid = _.uniqueId('c'); + this.changed = {}; + this._silent = {}; + this._pending = {}; + this.set(attributes, {silent: true}); + // Reset change tracking. + this.changed = {}; + this._silent = {}; + this._pending = {}; + this._previousAttributes = _.clone(this.attributes); + this.initialize.apply(this, arguments); + }; + + // Attach all inheritable methods to the Model prototype. + _.extend(Model.prototype, Events, { + + // A hash of attributes whose current and previous value differ. + changed: null, + + // A hash of attributes that have silently changed since the last time + // `change` was called. Will become pending attributes on the next call. + _silent: null, + + // A hash of attributes that have changed since the last `'change'` event + // began. + _pending: null, + + // The default name for the JSON `id` attribute is `"id"`. MongoDB and + // CouchDB users may want to set this to `"_id"`. + idAttribute: 'id', + + // Initialize is an empty function by default. Override it with your own + // initialization logic. + initialize: function(){}, + + // Return a copy of the model's `attributes` object. + toJSON: function(options) { + return _.clone(this.attributes); + }, + + // Proxy `Backbone.sync` by default. + sync: function() { + return Backbone.sync.apply(this, arguments); + }, + + // Get the value of an attribute. + get: function(attr) { + return this.attributes[attr]; + }, + + // Get the HTML-escaped value of an attribute. + escape: function(attr) { + var html; + if (html = this._escapedAttributes[attr]) return html; + var val = this.get(attr); + return this._escapedAttributes[attr] = _.escape(val == null ? '' : '' + val); + }, + + // Returns `true` if the attribute contains a value that is not null + // or undefined. + has: function(attr) { + return this.get(attr) != null; + }, + + // Set a hash of model attributes on the object, firing `"change"` unless + // you choose to silence it. + set: function(key, value, options) { + var attrs, attr, val; + + // Handle both `"key", value` and `{key: value}` -style arguments. + if (_.isObject(key) || key == null) { + attrs = key; + options = value; + } else { + attrs = {}; + attrs[key] = value; + } + + // Extract attributes and options. + options || (options = {}); + if (!attrs) return this; + if (attrs instanceof Model) attrs = attrs.attributes; + if (options.unset) for (attr in attrs) attrs[attr] = void 0; + + // Run validation. + if (!this._validate(attrs, options)) return false; + + // Check for changes of `id`. + if (this.idAttribute in attrs) this.id = attrs[this.idAttribute]; + + var changes = options.changes = {}; + var now = this.attributes; + var escaped = this._escapedAttributes; + var prev = this._previousAttributes || {}; + + // For each `set` attribute... + for (attr in attrs) { + val = attrs[attr]; + + // If the new and current value differ, record the change. + if (!_.isEqual(now[attr], val) || (options.unset && _.has(now, attr))) { + delete escaped[attr]; + (options.silent ? this._silent : changes)[attr] = true; + } + + // Update or delete the current value. + options.unset ? delete now[attr] : now[attr] = val; + + // If the new and previous value differ, record the change. If not, + // then remove changes for this attribute. + if (!_.isEqual(prev[attr], val) || (_.has(now, attr) != _.has(prev, attr))) { + this.changed[attr] = val; + if (!options.silent) this._pending[attr] = true; + } else { + delete this.changed[attr]; + delete this._pending[attr]; + } + } + + // Fire the `"change"` events. + if (!options.silent) this.change(options); + return this; + }, + + // Remove an attribute from the model, firing `"change"` unless you choose + // to silence it. `unset` is a noop if the attribute doesn't exist. + unset: function(attr, options) { + options = _.extend({}, options, {unset: true}); + return this.set(attr, null, options); + }, + + // Clear all attributes on the model, firing `"change"` unless you choose + // to silence it. + clear: function(options) { + options = _.extend({}, options, {unset: true}); + return this.set(_.clone(this.attributes), options); + }, + + // Fetch the model from the server. If the server's representation of the + // model differs from its current attributes, they will be overriden, + // triggering a `"change"` event. + fetch: function(options) { + options = options ? _.clone(options) : {}; + var model = this; + var success = options.success; + options.success = function(resp, status, xhr) { + if (!model.set(model.parse(resp, xhr), options)) return false; + if (success) success(model, resp, options); + model.trigger('sync', model, resp, options); + }; + options.error = Backbone.wrapError(options.error, model, options); + return this.sync('read', this, options); + }, + + // Set a hash of model attributes, and sync the model to the server. + // If the server returns an attributes hash that differs, the model's + // state will be `set` again. + save: function(key, value, options) { + var attrs, current, done; + + // Handle both `("key", value)` and `({key: value})` -style calls. + if (_.isObject(key) || key == null) { + attrs = key; + options = value; + } else { + attrs = {}; + attrs[key] = value; + } + options = options ? _.clone(options) : {}; + + // If we're "wait"-ing to set changed attributes, validate early. + if (options.wait) { + if (!this._validate(attrs, options)) return false; + current = _.clone(this.attributes); + } + + // Regular saves `set` attributes before persisting to the server. + var silentOptions = _.extend({}, options, {silent: true}); + if (attrs && !this.set(attrs, options.wait ? silentOptions : options)) { + return false; + } + + // Do not persist invalid models. + if (!attrs && !this.isValid()) return false; + + // After a successful server-side save, the client is (optionally) + // updated with the server-side state. + var model = this; + var success = options.success; + options.success = function(resp, status, xhr) { + done = true; + var serverAttrs = model.parse(resp, xhr); + if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs); + if (!model.set(serverAttrs, options)) return false; + if (success) success(model, resp, options); + model.trigger('sync', model, resp, options); + }; + + // Finish configuring and sending the Ajax request. + options.error = Backbone.wrapError(options.error, model, options); + var xhr = this.sync(this.isNew() ? 'create' : 'update', this, options); + + // When using `wait`, reset attributes to original values unless + // `success` has been called already. + if (!done && options.wait) { + this.clear(silentOptions); + this.set(current, silentOptions); + } + + return xhr; + }, + + // Destroy this model on the server if it was already persisted. + // Optimistically removes the model from its collection, if it has one. + // If `wait: true` is passed, waits for the server to respond before removal. + destroy: function(options) { + options = options ? _.clone(options) : {}; + var model = this; + var success = options.success; + + var destroy = function() { + model.trigger('destroy', model, model.collection, options); + }; + + options.success = function(resp) { + if (options.wait || model.isNew()) destroy(); + if (success) success(model, resp, options); + if (!model.isNew()) model.trigger('sync', model, resp, options); + }; + + if (this.isNew()) { + options.success(); + return false; + } + + options.error = Backbone.wrapError(options.error, model, options); + var xhr = this.sync('delete', this, options); + if (!options.wait) destroy(); + return xhr; + }, + + // Default URL for the model's representation on the server -- if you're + // using Backbone's restful methods, override this to change the endpoint + // that will be called. + url: function() { + var base = getValue(this, 'urlRoot') || getValue(this.collection, 'url') || urlError(); + if (this.isNew()) return base; + return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + encodeURIComponent(this.id); + }, + + // **parse** converts a response into the hash of attributes to be `set` on + // the model. The default implementation is just to pass the response along. + parse: function(resp, xhr) { + return resp; + }, + + // Create a new model with identical attributes to this one. + clone: function() { + return new this.constructor(this.attributes); + }, + + // A model is new if it has never been saved to the server, and lacks an id. + isNew: function() { + return this.id == null; + }, + + // Call this method to manually fire a `"change"` event for this model and + // a `"change:attribute"` event for each changed attribute. + // Calling this will cause all objects observing the model to update. + change: function(options) { + options || (options = {}); + var changing = this._changing; + this._changing = true; + + // Silent changes become pending changes. + for (var attr in this._silent) this._pending[attr] = true; + + // Silent changes are triggered. + var changes = _.extend({}, options.changes, this._silent); + this._silent = {}; + for (var attr in changes) { + this.trigger('change:' + attr, this, this.get(attr), options); + } + if (changing) return this; + + // Continue firing `"change"` events while there are pending changes. + while (!_.isEmpty(this._pending)) { + this._pending = {}; + this.trigger('change', this, options); + // Pending and silent changes still remain. + for (var attr in this.changed) { + if (this._pending[attr] || this._silent[attr]) continue; + delete this.changed[attr]; + } + this._previousAttributes = _.clone(this.attributes); + } + + this._changing = false; + return this; + }, + + // Determine if the model has changed since the last `"change"` event. + // If you specify an attribute name, determine if that attribute has changed. + hasChanged: function(attr) { + if (attr == null) return !_.isEmpty(this.changed); + return _.has(this.changed, attr); + }, + + // Return an object containing all the attributes that have changed, or + // false if there are no changed attributes. Useful for determining what + // parts of a view need to be updated and/or what attributes need to be + // persisted to the server. Unset attributes will be set to undefined. + // You can also pass an attributes object to diff against the model, + // determining if there *would be* a change. + changedAttributes: function(diff) { + if (!diff) return this.hasChanged() ? _.clone(this.changed) : false; + var val, changed = false, old = this._previousAttributes; + for (var attr in diff) { + if (_.isEqual(old[attr], (val = diff[attr]))) continue; + (changed || (changed = {}))[attr] = val; + } + return changed; + }, + + // Get the previous value of an attribute, recorded at the time the last + // `"change"` event was fired. + previous: function(attr) { + if (attr == null || !this._previousAttributes) return null; + return this._previousAttributes[attr]; + }, + + // Get all of the attributes of the model at the time of the previous + // `"change"` event. + previousAttributes: function() { + return _.clone(this._previousAttributes); + }, + + // Check if the model is currently in a valid state. It's only possible to + // get into an *invalid* state if you're using silent changes. + isValid: function() { + return !this.validate || !this.validate(this.attributes); + }, + + // Run validation against the next complete set of model attributes, + // returning `true` if all is well. If a specific `error` callback has + // been passed, call that instead of firing the general `"error"` event. + _validate: function(attrs, options) { + if (options.silent || !this.validate) return true; + attrs = _.extend({}, this.attributes, attrs); + var error = this.validate(attrs, options); + if (!error) return true; + if (options && options.error) { + options.error(this, error, options); + } else { + this.trigger('error', this, error, options); + } + return false; + } + + }); + + // Backbone.Collection + // ------------------- + + // Provides a standard collection class for our sets of models, ordered + // or unordered. If a `comparator` is specified, the Collection will maintain + // its models in sort order, as they're added and removed. + var Collection = Backbone.Collection = function(models, options) { + options || (options = {}); + if (options.model) this.model = options.model; + if (options.comparator !== undefined) this.comparator = options.comparator; + this._reset(); + this.initialize.apply(this, arguments); + if (models) this.reset(models, {silent: true, parse: options.parse}); + }; + + // Define the Collection's inheritable methods. + _.extend(Collection.prototype, Events, { + + // The default model for a collection is just a **Backbone.Model**. + // This should be overridden in most cases. + model: Model, + + // Initialize is an empty function by default. Override it with your own + // initialization logic. + initialize: function(){}, + + // The JSON representation of a Collection is an array of the + // models' attributes. + toJSON: function(options) { + return this.map(function(model){ return model.toJSON(options); }); + }, + + // Proxy `Backbone.sync` by default. + sync: function() { + return Backbone.sync.apply(this, arguments); + }, + + // Add a model, or list of models to the set. Pass **silent** to avoid + // firing the `add` event for every new model. + add: function(models, options) { + var i, index, length, model, cid, id, cids = {}, ids = {}, dups = []; + options || (options = {}); + models = _.isArray(models) ? models.slice() : [models]; + + // Begin by turning bare objects into model references, and preventing + // invalid models or duplicate models from being added. + for (i = 0, length = models.length; i < length; i++) { + if (!(model = models[i] = this._prepareModel(models[i], options))) { + throw new Error("Can't add an invalid model to a collection"); + } + cid = model.cid; + id = model.id; + if (cids[cid] || this._byCid[cid] || ((id != null) && (ids[id] || this._byId[id]))) { + dups.push(i); + continue; + } + cids[cid] = ids[id] = model; + } + + // Remove duplicates. + i = dups.length; + while (i--) { + dups[i] = models.splice(dups[i], 1)[0]; + } + + // Listen to added models' events, and index models for lookup by + // `id` and by `cid`. + for (i = 0, length = models.length; i < length; i++) { + (model = models[i]).on('all', this._onModelEvent, this); + this._byCid[model.cid] = model; + if (model.id != null) this._byId[model.id] = model; + } + + // Insert models into the collection, re-sorting if needed, and triggering + // `add` events unless silenced. + this.length += length; + index = options.at != null ? options.at : this.models.length; + splice.apply(this.models, [index, 0].concat(models)); + + // Merge in duplicate models. + if (options.merge) { + for (i = 0, length = dups.length; i < length; i++) { + if (model = this._byId[dups[i].id]) { + model.set(dups[i], options); + } + } + } + + // Sort the collection if appropriate. + if (this.comparator && options.at == null) this.sort({silent: true}); + + if (options.silent) return this; + for (i = 0, length = this.models.length; i < length; i++) { + if (!cids[(model = this.models[i]).cid]) continue; + options.index = i; + model.trigger('add', model, this, options); + } + + return this; + }, + + // Remove a model, or a list of models from the set. Pass silent to avoid + // firing the `remove` event for every model removed. + remove: function(models, options) { + var i, l, index, model; + options || (options = {}); + models = _.isArray(models) ? models.slice() : [models]; + for (i = 0, l = models.length; i < l; i++) { + model = this.getByCid(models[i]) || this.get(models[i]); + if (!model) continue; + delete this._byId[model.id]; + delete this._byCid[model.cid]; + index = this.indexOf(model); + this.models.splice(index, 1); + this.length--; + if (!options.silent) { + options.index = index; + model.trigger('remove', model, this, options); + } + this._removeReference(model); + } + return this; + }, + + // Add a model to the end of the collection. + push: function(model, options) { + model = this._prepareModel(model, options); + this.add(model, options); + return model; + }, + + // Remove a model from the end of the collection. + pop: function(options) { + var model = this.at(this.length - 1); + this.remove(model, options); + return model; + }, + + // Add a model to the beginning of the collection. + unshift: function(model, options) { + model = this._prepareModel(model, options); + this.add(model, _.extend({at: 0}, options)); + return model; + }, + + // Remove a model from the beginning of the collection. + shift: function(options) { + var model = this.at(0); + this.remove(model, options); + return model; + }, + + // Slice out a sub-array of models from the collection. + slice: function(begin, end) { + return this.models.slice(begin, end); + }, + + // Get a model from the set by id. + get: function(id) { + if (id == null) return void 0; + return this._byId[id.id != null ? id.id : id]; + }, + + // Get a model from the set by client id. + getByCid: function(cid) { + return cid && this._byCid[cid.cid || cid]; + }, + + // Get the model at the given index. + at: function(index) { + return this.models[index]; + }, + + // Return models with matching attributes. Useful for simple cases of `filter`. + where: function(attrs) { + if (_.isEmpty(attrs)) return []; + return this.filter(function(model) { + for (var key in attrs) { + if (attrs[key] !== model.get(key)) return false; + } + return true; + }); + }, + + // Force the collection to re-sort itself. You don't need to call this under + // normal circumstances, as the set will maintain sort order as each item + // is added. + sort: function(options) { + options || (options = {}); + if (!this.comparator) throw new Error('Cannot sort a set without a comparator'); + var boundComparator = _.bind(this.comparator, this); + if (this.comparator.length == 1) { + this.models = this.sortBy(boundComparator); + } else { + this.models.sort(boundComparator); + } + if (!options.silent) this.trigger('reset', this, options); + return this; + }, + + // Pluck an attribute from each model in the collection. + pluck: function(attr) { + return _.map(this.models, function(model){ return model.get(attr); }); + }, + + // When you have more items than you want to add or remove individually, + // you can reset the entire set with a new list of models, without firing + // any `add` or `remove` events. Fires `reset` when finished. + reset: function(models, options) { + models || (models = []); + options || (options = {}); + for (var i = 0, l = this.models.length; i < l; i++) { + this._removeReference(this.models[i]); + } + this._reset(); + this.add(models, _.extend({silent: true}, options)); + if (!options.silent) this.trigger('reset', this, options); + return this; + }, + + // Fetch the default set of models for this collection, resetting the + // collection when they arrive. If `add: true` is passed, appends the + // models to the collection instead of resetting. + fetch: function(options) { + options = options ? _.clone(options) : {}; + if (options.parse === undefined) options.parse = true; + var collection = this; + var success = options.success; + options.success = function(resp, status, xhr) { + collection[options.add ? 'add' : 'reset'](collection.parse(resp, xhr), options); + if (success) success(collection, resp, options); + collection.trigger('sync', collection, resp, options); + }; + options.error = Backbone.wrapError(options.error, collection, options); + return this.sync('read', this, options); + }, + + // Create a new instance of a model in this collection. Add the model to the + // collection immediately, unless `wait: true` is passed, in which case we + // wait for the server to agree. + create: function(model, options) { + var coll = this; + options = options ? _.clone(options) : {}; + model = this._prepareModel(model, options); + if (!model) return false; + if (!options.wait) coll.add(model, options); + var success = options.success; + options.success = function(model, resp, options) { + if (options.wait) coll.add(model, options); + if (success) success(model, resp, options); + }; + model.save(null, options); + return model; + }, + + // **parse** converts a response into a list of models to be added to the + // collection. The default implementation is just to pass it through. + parse: function(resp, xhr) { + return resp; + }, + + // Create a new collection with an identical list of models as this one. + clone: function() { + return new this.constructor(this.models); + }, + + // Proxy to _'s chain. Can't be proxied the same way the rest of the + // underscore methods are proxied because it relies on the underscore + // constructor. + chain: function() { + return _(this.models).chain(); + }, + + // Reset all internal state. Called when the collection is reset. + _reset: function(options) { + this.length = 0; + this.models = []; + this._byId = {}; + this._byCid = {}; + }, + + // Prepare a model or hash of attributes to be added to this collection. + _prepareModel: function(attrs, options) { + if (attrs instanceof Model) { + if (!attrs.collection) attrs.collection = this; + return attrs; + } + options || (options = {}); + options.collection = this; + var model = new this.model(attrs, options); + if (!model._validate(model.attributes, options)) return false; + return model; + }, + + // Internal method to remove a model's ties to a collection. + _removeReference: function(model) { + if (this == model.collection) { + delete model.collection; + } + model.off('all', this._onModelEvent, this); + }, + + // Internal method called every time a model in the set fires an event. + // Sets need to update their indexes when models change ids. All other + // events simply proxy through. "add" and "remove" events that originate + // in other collections are ignored. + _onModelEvent: function(event, model, collection, options) { + if ((event == 'add' || event == 'remove') && collection != this) return; + if (event == 'destroy') { + this.remove(model, options); + } + if (model && event === 'change:' + model.idAttribute) { + delete this._byId[model.previous(model.idAttribute)]; + if (model.id != null) this._byId[model.id] = model; + } + this.trigger.apply(this, arguments); + } + + }); + + // Underscore methods that we want to implement on the Collection. + var methods = ['forEach', 'each', 'map', 'reduce', 'reduceRight', 'find', + 'detect', 'filter', 'select', 'reject', 'every', 'all', 'some', 'any', + 'include', 'contains', 'invoke', 'max', 'min', 'sortBy', 'sortedIndex', + 'toArray', 'size', 'first', 'initial', 'rest', 'last', 'without', 'indexOf', + 'shuffle', 'lastIndexOf', 'isEmpty', 'groupBy']; + + // Mix in each Underscore method as a proxy to `Collection#models`. + _.each(methods, function(method) { + Collection.prototype[method] = function() { + return _[method].apply(_, [this.models].concat(_.toArray(arguments))); + }; + }); + + // Backbone.Router + // ------------------- + + // Routers map faux-URLs to actions, and fire events when routes are + // matched. Creating a new one sets its `routes` hash, if not set statically. + var Router = Backbone.Router = function(options) { + options || (options = {}); + if (options.routes) this.routes = options.routes; + this._bindRoutes(); + this.initialize.apply(this, arguments); + }; + + // Cached regular expressions for matching named param parts and splatted + // parts of route strings. + var namedParam = /:\w+/g; + var splatParam = /\*\w+/g; + var escapeRegExp = /[-[\]{}()+?.,\\^$|#\s]/g; + + // Set up all inheritable **Backbone.Router** properties and methods. + _.extend(Router.prototype, Events, { + + // Initialize is an empty function by default. Override it with your own + // initialization logic. + initialize: function(){}, + + // Manually bind a single named route to a callback. For example: + // + // this.route('search/:query/p:num', 'search', function(query, num) { + // ... + // }); + // + route: function(route, name, callback) { + Backbone.history || (Backbone.history = new History); + if (!_.isRegExp(route)) route = this._routeToRegExp(route); + if (!callback) callback = this[name]; + Backbone.history.route(route, _.bind(function(fragment) { + var args = this._extractParameters(route, fragment); + callback && callback.apply(this, args); + this.trigger.apply(this, ['route:' + name].concat(args)); + Backbone.history.trigger('route', this, name, args); + }, this)); + return this; + }, + + // Simple proxy to `Backbone.history` to save a fragment into the history. + navigate: function(fragment, options) { + Backbone.history.navigate(fragment, options); + }, + + // Bind all defined routes to `Backbone.history`. We have to reverse the + // order of the routes here to support behavior where the most general + // routes can be defined at the bottom of the route map. + _bindRoutes: function() { + if (!this.routes) return; + var routes = []; + for (var route in this.routes) { + routes.unshift([route, this.routes[route]]); + } + for (var i = 0, l = routes.length; i < l; i++) { + this.route(routes[i][0], routes[i][1], this[routes[i][1]]); + } + }, + + // Convert a route string into a regular expression, suitable for matching + // against the current location hash. + _routeToRegExp: function(route) { + route = route.replace(escapeRegExp, '\\$&') + .replace(namedParam, '([^\/]+)') + .replace(splatParam, '(.*?)'); + return new RegExp('^' + route + '$'); + }, + + // Given a route, and a URL fragment that it matches, return the array of + // extracted parameters. + _extractParameters: function(route, fragment) { + return route.exec(fragment).slice(1); + } + + }); + + // Backbone.History + // ---------------- + + // Handles cross-browser history management, based on URL fragments. If the + // browser does not support `onhashchange`, falls back to polling. + var History = Backbone.History = function(options) { + this.handlers = []; + _.bindAll(this, 'checkUrl'); + this.location = options && options.location || root.location; + this.history = options && options.history || root.history; + }; + + // Cached regex for cleaning leading hashes and slashes . + var routeStripper = /^[#\/]/; + + // Cached regex for detecting MSIE. + var isExplorer = /msie [\w.]+/; + + // Cached regex for removing a trailing slash. + var trailingSlash = /\/$/; + + // Has the history handling already been started? + History.started = false; + + // Set up all inheritable **Backbone.History** properties and methods. + _.extend(History.prototype, Events, { + + // The default interval to poll for hash changes, if necessary, is + // twenty times a second. + interval: 50, + + // Gets the true hash value. Cannot use location.hash directly due to bug + // in Firefox where location.hash will always be decoded. + getHash: function(window) { + var match = (window || this).location.href.match(/#(.*)$/); + return match ? match[1] : ''; + }, + + // Get the cross-browser normalized URL fragment, either from the URL, + // the hash, or the override. + getFragment: function(fragment, forcePushState) { + if (fragment == null) { + if (this._hasPushState || !this._wantsHashChange || forcePushState) { + fragment = this.location.pathname; + var root = this.options.root.replace(trailingSlash, ''); + if (!fragment.indexOf(root)) fragment = fragment.substr(root.length); + } else { + fragment = this.getHash(); + } + } + return decodeURIComponent(fragment.replace(routeStripper, '')); + }, + + // Start the hash change handling, returning `true` if the current URL matches + // an existing route, and `false` otherwise. + start: function(options) { + if (History.started) throw new Error("Backbone.history has already been started"); + History.started = true; + + // Figure out the initial configuration. Do we need an iframe? + // Is pushState desired ... is it available? + this.options = _.extend({}, {root: '/'}, this.options, options); + this._wantsHashChange = this.options.hashChange !== false; + this._wantsPushState = !!this.options.pushState; + this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState); + var fragment = this.getFragment(); + var docMode = document.documentMode; + var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7)); + + if (oldIE && this._wantsHashChange) { + this.iframe = Backbone.$('