Compare commits

..

1 Commits
3.7.0 ... 1.0.2

Author SHA1 Message Date
jdalton
7467a2a2eb Bump to v1.0.2. 2013-02-18 03:13:40 -07:00
101 changed files with 53063 additions and 57857 deletions

View File

@@ -1,18 +0,0 @@
# This file is for unifying the coding style for different editors and IDEs
# editorconfig.org
root = true
[*]
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
[**.{js,json,md}]
indent_style = space
indent_size = 2
insert_final_newline = true
[**.html]
indent_style = tab
insert_final_newline = false

7
.gitignore vendored
View File

@@ -1,6 +1,5 @@
.DS_Store
*.custom.*
*.log
*.map
lodash.compat.min.js
node_modules
node_modules/
vendor/closure-compiler/
vendor/uglifyjs/

12
.jamignore Normal file
View File

@@ -0,0 +1,12 @@
.*
*.custom.*
*.md
*.txt
build.js
index.js
build/
doc/
node_modules/
perf/
test/
vendor/

26
.npmignore Normal file
View File

@@ -0,0 +1,26 @@
.*
*.custom.*
*.d.ts
CONTRIBUTING.md
doc/*.php
node_modules/
perf/*.html
perf/*-ui.js
perf/*.sh
test/*.html
test/*-ui.js
test/*.sh
vendor/*.gz
vendor/backbone/
vendor/benchmark.js/*.jar
vendor/closure-compiler/
vendor/docdown/
vendor/firebug-lite/
vendor/json3/
vendor/jquery/
vendor/qunit/qunit/*.css
vendor/qunit/qunit/*-1.8.0.js
vendor/requirejs/
vendor/underscore/*-min.js
vendor/uglifyjs/
vendor/underscore/test/

View File

@@ -1,77 +1,20 @@
language: node_js
node_js:
- "0.12"
- 0.6
- 0.9
env:
global:
- PATTERN1="s|^.+?!support\.funcNames\b[\s\S]+?\.name\b[\s\S]+?\}\n||m"
- PATTERN2="s|\s*else\s*\{\s*iteratee\(index\);\s*\}||"
- BIN="node" BUILD="compat" ISTANBUL=false OPTION=""
- NPM_VERSION="^2.0.0" SAUCE_LABS=false SAUCE_USERNAME="lodash"
- secure: "tg1JFsIFnxzLaTboFPOnm+aJCuMm5+JdhLlESlqg9x3fwro++7KCnwHKLNovhchaPe4otC43ZMB/nfWhDnDm11dKbm/V6HlTkED+dadTsaLxVDg6J+7yK41QhokBPJOxLV78iDaNaAQVYEirAgZ0yn8kFubxmNKV+bpCGQNc9yU="
matrix:
- BUILD="compat"
- BUILD="modern"
- BUILD="modern"
- BUILD="modern" ISTANBUL=true
- BIN="phantomjs"
- BIN="rhino"
- BIN="rhino" OPTION="-require"
- BIN="ringo"
matrix:
include:
- node_js: "io.js"
env:
- node_js: "io.js"
env: BUILD="modern"
- node_js: "0.8"
env: NPM_VERSION="~1.4.0"
- node_js: "0.8"
env: BUILD="modern" NPM_VERSION="~1.4.0"
- node_js: "0.10"
env:
- node_js: "0.10"
env: BUILD="modern"
- node_js: "0.12"
env: SAUCE_LABS=true
- node_js: "0.12"
env: SAUCE_LABS=true BUILD="modern"
- TEST_COMMAND="phantomjs ./test/test.js ../dist/lodash.compat.js"
- TEST_COMMAND="phantomjs ./test/test.js ../dist/lodash.compat.min.js"
- TEST_COMMAND="node ./test/test.js ../dist/lodash.js"
- TEST_COMMAND="node ./test/test.js ../dist/lodash.min.js"
- TEST_COMMAND="node ./test/test-build.js --time-limit 49m40s"
git:
depth: 10
depth: 1
branches:
only:
- master
notifications:
webhooks:
urls:
- https://webhooks.gitter.im/e/4aab6358b0e9aed0b628
on_success: change
on_failure: always
before_install:
- "nvm use $TRAVIS_NODE_VERSION"
- "npm config set loglevel error"
- "npm i -g npm@\"$NPM_VERSION\""
- "[ $SAUCE_LABS == false ] || npm i chalk@\"^1.0.0\" ecstatic@\"0.7.3\" request@\"^2.0.0\" sauce-tunnel@\"2.2.3\""
- "[ $ISTANBUL == false ] || (npm i -g coveralls@\"^2.0.0\" && npm i istanbul@\"0.3.13\")"
- "[ $BIN != 'rhino' ] || (sudo mkdir /opt/rhino-1.7R5 && sudo wget --no-check-certificate -O $_/js.jar https://lodash.com/_travis/rhino-1.7R5.jar)"
- "[ $BIN != 'rhino' ] || (echo -e '#!/bin/sh\\njava -jar /opt/rhino-1.7R5/js.jar $@' | sudo tee /usr/local/bin/rhino && sudo chmod +x /usr/local/bin/rhino)"
- "[ $BIN != 'ringo' ] || (wget --no-check-certificate https://lodash.com/_travis/ringojs-0.11.zip && sudo unzip ringojs-0.11 -d /opt && rm ringojs-0.11.zip)"
- "[ $BIN != 'ringo' ] || (sudo ln -s /opt/ringojs-0.11/bin/ringo /usr/local/bin/ringo && sudo chmod +x $_)"
- "perl -pi -e 's|\"lodash\"|\"lodash-compat\"|' ./package.json"
- "git clone --depth=10 --branch=master git://github.com/lodash/lodash-cli.git ./node_modules/lodash-cli && mkdir $_/node_modules && cd $_ && ln -s ../../../ ./lodash-compat && cd ../ && npm i && cd ../../"
- "node ./node_modules/lodash-cli/bin/lodash $BUILD -o ./lodash.$BUILD.js"
before_script:
- "tar -xzvf vendor/closure-compiler.tar.gz -C vendor"
- "tar -xzvf vendor/uglifyjs.tar.gz -C vendor"
script:
- "[ $ISTANBUL == false ] || cp ./lodash.$BUILD.js ./lodash.js"
- "[ $ISTANBUL == false ] || perl -0pi -e \"$PATTERN1\" ./lodash.js && perl -0pi -e \"$PATTERN2\" $_"
- "[ $ISTANBUL == false ] || node ./node_modules/istanbul/lib/cli.js cover -x \"**/vendor/**\" --report lcovonly ./test/test.js -- ./lodash.js"
- "[ $ISTANBUL == false ] || [ $TRAVIS_SECURE_ENV_VARS == false ] || (cat ./coverage/lcov.info | coveralls)"
- "[ $SAUCE_LABS == true ] || [ $ISTANBUL == true ] || cd ./test"
- "[ $SAUCE_LABS == true ] || [ $ISTANBUL == true ] || $BIN $OPTION ./test.js ../lodash.$BUILD.js"
- "[ $SAUCE_LABS == true ] || [ $ISTANBUL == true ] || [ $TRAVIS_SECURE_ENV_VARS == false ] || $BIN $OPTION ./test.js ../lodash.$BUILD.min.js"
- "[ $SAUCE_LABS == false ] || $BIN ./test/saucelabs.js name=\"lodash tests\" runner=\"test/index.html?build=../lodash.$BUILD.js&noglobals=true\" tags=\"$BUILD,development\""
- "[ $SAUCE_LABS == false ] || $BIN ./test/saucelabs.js name=\"lodash tests\" runner=\"test/index.html?build=../lodash.$BUILD.min.js&noglobals=true\" tags=\"$BUILD,production\""
- "[ $SAUCE_LABS == false ] || [ $BUILD != 'compat' ] || $BIN ./test/saucelabs.js name=\"lodash tests\" runner=\"test/index.html?build=../lodash.$BUILD.js\" tags=\"$BUILD,development,ie-compat\" compatMode=7"
- "[ $SAUCE_LABS == false ] || [ $BUILD != 'compat' ] || $BIN ./test/saucelabs.js name=\"lodash tests\" runner=\"test/index.html?build=../lodash.$BUILD.min.js\" tags=\"$BUILD,production,ie-compat\" compatMode=7"
- "[ $SAUCE_LABS == false ] || $BIN ./test/saucelabs.js name=\"backbone tests\" runner=\"test/backbone.html?build=../lodash.$BUILD.min.js\" tags=\"$BUILD,production,backbone\""
- "[ $SAUCE_LABS == false ] || $BIN ./test/saucelabs.js name=\"backbone tests\" runner=\"test/backbone.html?build=../lodash.$BUILD.js\" tags=\"$BUILD,development,backbone\""
- "[ $SAUCE_LABS == false ] || $BIN ./test/saucelabs.js name=\"underscore tests\" runner=\"test/underscore.html?build=../lodash.$BUILD.min.js\" tags=\"$BUILD,production,underscore\""
- "[ $SAUCE_LABS == false ] || $BIN ./test/saucelabs.js name=\"underscore tests\" runner=\"test/underscore.html?build=../lodash.$BUILD.js\" tags=\"$BUILD,development,underscore\""
$TEST_COMMAND

View File

@@ -1,25 +1,21 @@
# Contributing to lodash
# Contributing to Lo-Dash
If youd like to contribute a feature or bug fix, you can [fork](https://help.github.com/articles/fork-a-repo/) lodash, commit your changes, & [send a pull request](https://help.github.com/articles/using-pull-requests/).
Please make sure to [search the issue tracker](https://github.com/lodash/lodash/issues) first; your issue may have already been discussed or fixed in `master`.
If youd like to contribute a feature or bug fix, you can [fork](https://help.github.com/articles/fork-a-repo) Lo-Dash, commit your changes, and [send a pull request](https://help.github.com/articles/using-pull-requests).
Please make sure to [search the issue tracker](https://github.com/bestiejs/lodash/issues) first; your issue may have already been discussed or fixed in `master`.
## Tests
Include updated unit tests in the `test` directory as part of your pull request.
Dont worry about regenerating the documentation, lodash.js, or lodash.min.js.
Before running the unit tests youll need to install, `npm i`, [development dependencies](https://docs.npmjs.com/files/package.json#devdependencies).
Run unit tests from the command-line via `node test/test`, or open `test/index.html` in a web browser.
The `test/run-test.sh` script attempts to run the tests in [Rhino](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino), [RingoJS](http://ringojs.org/), [PhantomJS](http://phantomjs.org/), & [Node](http://nodejs.org/), before running them in your default browser.
The [Backbone](http://backbonejs.org/) & [Underscore](http://underscorejs.org/) test suites are included as well.
You can run the tests from the command line via `npm test`, or open `test/index.html` in a web browser.
The `test/run-test.sh` script attempts to run the tests in [Rhino](https://developer.mozilla.org/en-US/docs/Rhino), [Narwhal](https://github.com/280north/narwhal), [RingoJS](http://ringojs.org/), [PhantomJS](http://phantomjs.org/), and [Node](http://nodejs.org/), before running them in your default browser.
The [Backbone](http://backbonejs.org/) and [Underscore](http://http://underscorejs.org/) test suites are included as well.
## Contributor License Agreement
lodash is a member of the [Dojo Foundation](http://dojofoundation.org/).
Lo-Dash is a member of the [Dojo Foundation](http://dojofoundation.org/).
As such, we request that all contributors sign the Dojo Foundation [contributor license agreement](http://dojofoundation.org/about/claForm).
For more information about CLAs, please check out Alex Russells excellent post, [Why Do I Need to Sign This?](http://infrequently.org/2008/06/why-do-i-need-to-sign-this/).
For more information about CLAs, please check out Alex Russells excellent post, ["Why Do I Need to Sign This?"](http://infrequently.org/2008/06/why-do-i-need-to-sign-this/).
## Coding Guidelines
@@ -29,11 +25,11 @@ In addition to the following guidelines, please follow the conventions already e
Use two spaces for indentation. No tabs.
- **Naming**:<br>
Keep variable & method names concise & descriptive.<br>
Variable names `index`, `collection`, & `callback` are preferable to `i`, `arr`, & `fn`.
Keep variable and method names concise and descriptive.<br>
Variable names `index`, `collection`, and `callback` are preferable to `i`, `arr`, and `fn`.
- **Quotes**:<br>
Single-quoted strings are preferred to double-quoted strings; however, please use a double-quoted string if the value contains a single-quote character to avoid unnecessary escaping.
- **Comments**:<br>
Please use single-line comments to annotate significant additions, & [JSDoc-style](http://www.2ality.com/2011/08/jsdoc-intro.html) comments for new methods.
Please use single-line comments to annotate significant additions, and [JSDoc-style](http://www.2ality.com/2011/08/jsdoc-intro.html) comments for new methods.

View File

@@ -1,6 +1,6 @@
Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
Based on Underscore.js, copyright 2009-2015 Jeremy Ashkenas,
DocumentCloud and Investigative Reporters & Editors <http://underscorejs.org/>
Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
Based on Underscore.js 1.4.3, copyright 2009-2013 Jeremy Ashkenas,
DocumentCloud Inc. <http://underscorejs.org/>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
@@ -19,4 +19,4 @@ 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.
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

137
README.md
View File

@@ -1,29 +1,128 @@
# lodash v3.7.0
# Lo-Dash v1.0.2
The [modern build](https://github.com/lodash/lodash/wiki/Build-Differences) of [lodash](https://lodash.com/) with packages for [Bower](http://bower.io/), [Component](http://component.github.io/), & [Volo](http://volojs.org/).
A utility library delivering consistency, [customization](https://lodash.com/custom-builds), [performance](https://lodash.com/benchmarks), & [extras](https://lodash.com/#features).
Generated using [lodash-cli](https://www.npmjs.com/package/lodash-cli):
```bash
$ lodash modern -o ./lodash.js
## Download
* Lo-Dash builds (for modern environments):<br>
[Development](https://raw.github.com/lodash/lodash/1.0.2/dist/lodash.js) and
[Production](https://raw.github.com/lodash/lodash/1.0.2/dist/lodash.min.js)
* Lo-Dash compatibility builds (for legacy and modern environments):<br>
[Development](https://raw.github.com/lodash/lodash/1.0.2/dist/lodash.compat.js) and
[Production](https://raw.github.com/lodash/lodash/1.0.2/dist/lodash.compat.min.js)
* Underscore compatibility builds:<br>
[Development](https://raw.github.com/lodash/lodash/1.0.2/dist/lodash.underscore.js) and
[Production](https://raw.github.com/lodash/lodash/1.0.2/dist/lodash.underscore.min.js)
* For optimal file size, [create a custom build](https://lodash.com/custom-builds) with only the features you need
## Dive in
Weve got [API docs](https://lodash.com/docs), [benchmarks](https://lodash.com/benchmarks), and [unit tests](https://lodash.com/tests).
For a list of upcoming features, check out our [roadmap](https://github.com/lodash/lodash/wiki/Roadmap).
The full changelog is available [here](https://github.com/lodash/lodash/wiki/Changelog).
## Installation and usage
In browsers:
```html
<script src="lodash.js"></script>
```
## Community
Using [`npm`](http://npmjs.org/):
[![Join the chat at https://gitter.im/lodash/lodash](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/lodash/lodash)
```bash
npm install lodash
## Module formats
npm install -g lodash
npm link lodash
```
lodash is also available in a variety of other builds & module formats.
To avoid potential issues, update `npm` before installing Lo-Dash:
* npm packages for [modern](https://www.npmjs.com/package/lodash), [compatibility](https://www.npmjs.com/package/lodash-compat), & [per method](https://www.npmjs.com/browse/keyword/lodash-modularized) builds
* AMD modules for [modern](https://github.com/lodash/lodash/tree/3.7.0-amd) & [compatibility](https://github.com/lodash/lodash-compat/tree/3.7.0-amd) builds
* ES modules for the [modern](https://github.com/lodash/lodash/tree/3.7.0-es) build
```bash
npm install npm -g
```
## Further Reading
In [Node.js](http://nodejs.org/) and [RingoJS v0.8.0+](http://ringojs.org/):
* [API Documentation](https://lodash.com/docs)
* [Build Differences](https://github.com/lodash/lodash/wiki/Build-Differences)
* [Changelog](https://github.com/lodash/lodash/wiki/Changelog)
* [Release Notes](https://github.com/lodash/lodash/releases)
* [Roadmap](https://github.com/lodash/lodash/wiki/Roadmap)
* [More Resources](https://github.com/lodash/lodash/wiki/Resources)
```js
var _ = require('lodash');
// or as a drop-in replacement for Underscore
var _ = require('lodash/lodash.underscore');
```
**Note:** If Lo-Dash is installed globally, run [`npm link lodash`](http://blog.nodejs.org/2011/03/23/npm-1-0-global-vs-local-installation/) in your projects root directory before requiring it.
In [RingoJS v0.7.0-](http://ringojs.org/):
```js
var _ = require('lodash')._;
```
In [Rhino](http://www.mozilla.org/rhino/):
```js
load('lodash.js');
```
In an AMD loader like [RequireJS](http://requirejs.org/):
```js
require({
'paths': {
'underscore': 'path/to/lodash'
}
},
['underscore'], function(_) {
console.log(_.VERSION);
});
```
## Resources
For more information check out these articles, screencasts, and other videos over Lo-Dash:
* Posts
- [Say “Hello” to Lo-Dash](http://kitcambridge.be/blog/say-hello-to-lo-dash/)
* Videos
- [Introducing Lo-Dash](https://vimeo.com/44154599)
- [Lo-Dash optimizations and custom builds](https://vimeo.com/44154601)
- [Lo-Dashs origin and why its a better utility belt](https://vimeo.com/44154600)
- [Unit testing in Lo-Dash](https://vimeo.com/45865290)
- [Lo-Dashs approach to native method use](https://vimeo.com/48576012)
- [CascadiaJS: Lo-Dash for a better utility belt](http://www.youtube.com/watch?v=dpPy4f_SeEk)
## Features
* AMD loader support ([RequireJS](http://requirejs.org/), [curl.js](https://github.com/cujojs/curl), etc.)
* [_(…)](https://lodash.com/docs#_) supports intuitive chaining
* [_.at](https://lodash.com/docs#at) for cherry-picking collection values
* [_.bindKey](https://lodash.com/docs#bindKey) for binding [*“lazy”* defined](http://michaux.ca/articles/lazy-function-definition-pattern) methods
* [_.cloneDeep](https://lodash.com/docs#cloneDeep) for deep cloning arrays and objects
* [_.contains](https://lodash.com/docs#contains) accepts a `fromIndex` argument
* [_.forEach](https://lodash.com/docs#forEach) is chainable and supports exiting iteration early
* [_.forIn](https://lodash.com/docs#forIn) for iterating over an objects own and inherited properties
* [_.forOwn](https://lodash.com/docs#forOwn) for iterating over an objects own properties
* [_.isPlainObject](https://lodash.com/docs#isPlainObject) checks if values are created by the `Object` constructor
* [_.merge](https://lodash.com/docs#merge) for a deep [_.extend](https://lodash.com/docs#extend)
* [_.partial](https://lodash.com/docs#partial) and [_.partialRight](https://lodash.com/docs#partialRight) for partial application without `this` binding
* [_.template](https://lodash.com/docs#template) supports [*“imports”* options](https://lodash.com/docs#templateSettings_imports), [ES6 template delimiters](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-7.8.6), and [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
* [_.where](https://lodash.com/docs#where) supports deep object comparisons
* [_.clone](https://lodash.com/docs#clone), [_.omit](https://lodash.com/docs#omit), [_.pick](https://lodash.com/docs#pick),
[and more…](https://lodash.com/docs "_.assign, _.cloneDeep, _.first, _.initial, _.isEqual, _.last, _.merge, _.rest") accept `callback` and `thisArg` arguments
* [_.contains](https://lodash.com/docs#contains), [_.size](https://lodash.com/docs#size), [_.toArray](https://lodash.com/docs#toArray),
[and more…](https://lodash.com/docs "_.at, _.countBy, _.every, _.filter, _.find, _.forEach, _.groupBy, _.invoke, _.map, _.max, _.min, _.pluck, _.reduce, _.reduceRight, _.reject, _.shuffle, _.some, _.sortBy, _.where") accept strings
* [_.filter](https://lodash.com/docs#filter), [_.find](https://lodash.com/docs#find), [_.map](https://lodash.com/docs#map),
[and more…](https://lodash.com/docs "_.countBy, _.every, _.first, _.groupBy, _.initial, _.last, _.max, _.min, _.reject, _.rest, _.some, _.sortBy, _.sortedIndex, _.uniq") support *“_.pluck”* and *“_.where”* `callback` shorthands
## Support
Lo-Dash has been tested in at least Chrome 5~24, Firefox 1~18, IE 6-10, Opera 9.25-12, Safari 3-6, Node.js 0.4.8-0.8.20, Narwhal 0.3.2, PhantomJS 1.8.1, RingoJS 0.9, and Rhino 1.7RC5.

View File

@@ -1,20 +0,0 @@
{
"name": "lodash",
"version": "3.7.0",
"main": "lodash.js",
"ignore": [
".*",
"*.custom.*",
"*.log",
"*.map",
"*.md",
"lodash.src.js",
"component.json",
"package.json",
"doc",
"node_modules",
"perf",
"test",
"vendor"
]
}

2509
build.js Executable file

File diff suppressed because it is too large Load Diff

753
build/minify.js Executable file
View File

@@ -0,0 +1,753 @@
#!/usr/bin/env node
;(function() {
'use strict';
/** Load Node modules */
var fs = require('fs'),
https = require('https'),
path = require('path'),
spawn = require('child_process').spawn,
zlib = require('zlib'),
tar = require('../vendor/tar/tar.js'),
_ = require('../lodash.js');
/** Load other modules */
var preprocess = require('./pre-compile.js'),
postprocess = require('./post-compile.js');
/** The Git object ID of `closure-compiler.tar.gz` */
var closureId = '23cf67d0f0b979d97631fc108a2a43bb82225994';
/** The Git object ID of `uglifyjs.tar.gz` */
var uglifyId = 'a934fb18f8fa2768c6a68de44b6e035fe96a268b';
/** The path of the directory that is the base of the repository */
var basePath = fs.realpathSync(path.join(__dirname, '..'));
/** The path of the `vendor` directory */
var vendorPath = path.join(basePath, 'vendor');
/** The path to the Closure Compiler `.jar` */
var closurePath = path.join(vendorPath, 'closure-compiler', 'compiler.jar');
/** The path to the UglifyJS module */
var uglifyPath = path.join(vendorPath, 'uglifyjs', 'tools', 'node.js');
/** The Closure Compiler command-line options */
var closureOptions = ['--warning_level=QUIET'];
/** The media type for raw blob data */
var mediaType = 'application/vnd.github.v3.raw';
/** Used to reference parts of the blob href */
var location = (function() {
var host = 'api.github.com',
origin = 'https://api.github.com',
pathname = '/repos/bestiejs/lodash/git/blobs';
return {
'host': host,
'href': origin + pathname,
'origin': origin,
'pathname': pathname
};
}());
/** The Closure Compiler optimization modes */
var optimizationModes = {
'simple': 'SIMPLE_OPTIMIZATIONS',
'advanced': 'ADVANCED_OPTIMIZATIONS'
};
/** Reassign `existsSync` for older versions of Node */
fs.existsSync || (fs.existsSync = path.existsSync);
/*--------------------------------------------------------------------------*/
/**
* Minifies a given Lo-Dash `source` and invokes the `options.onComplete`
* callback when finished. The `onComplete` callback is invoked with one
* argument; (outputSource).
*
* @param {Array|String} [source=''] The source to minify or array of commands.
* -o, --output - Write output to a given path/filename.
* -s, --silent - Skip status updates normally logged to the console.
* -t, --template - Applies template specific minifier options.
*
* @param {Object} [options={}] The options object.
* outputPath - Write output to a given path/filename.
* isSilent - Skip status updates normally logged to the console.
* isTemplate - Applies template specific minifier options.
* onComplete - The function called once minification has finished.
*/
function minify(source, options) {
// used to specify the source map URL
var sourceMapURL;
// used to specify the default minifer modes
var modes = ['simple', 'advanced', 'hybrid'];
source || (source = '');
options || (options = {});
// juggle arguments
if (Array.isArray(source)) {
// convert commands to an options object
options = source;
// used to report invalid command-line arguments
var invalidArgs = _.reject(options.slice(options[0] == 'node' ? 2 : 0), function(value, index, options) {
if (/^(?:-o|--output)$/.test(options[index - 1]) ||
/^modes=.*$/.test(value)) {
return true;
}
var result = [
'-o', '--output',
'-p', '--source-map',
'-s', '--silent',
'-t', '--template'
].indexOf(value) > -1;
if (!result && /^(?:-p|--source-map)$/.test(options[index - 1])) {
result = true;
sourceMapURL = value;
}
return result;
});
// report invalid arguments
if (invalidArgs.length) {
console.log(
'\n' +
'Invalid argument' + (invalidArgs.length > 1 ? 's' : '') +
' passed: ' + invalidArgs.join(', ')
);
return;
}
var filePath = options[options.length - 1],
isMapped = options.indexOf('-p') > -1 || options.indexOf('--source-map') > -1,
isSilent = options.indexOf('-s') > -1 || options.indexOf('--silent') > -1,
isTemplate = options.indexOf('-t') > -1 || options.indexOf('--template') > -1,
outputPath = path.join(path.dirname(filePath), path.basename(filePath, '.js') + '.min.js');
modes = options.reduce(function(result, value) {
var match = value.match(/modes=(.*)$/);
return match ? match[1].split(/, */) : result;
}, modes);
outputPath = options.reduce(function(result, value, index) {
if (/-o|--output/.test(value)) {
result = options[index + 1];
result = path.join(fs.realpathSync(path.dirname(result)), path.basename(result));
}
return result;
}, outputPath);
options = {
'filePath': filePath,
'isMapped': isMapped,
'isSilent': isSilent,
'isTemplate': isTemplate,
'modes': modes,
'outputPath': outputPath,
'sourceMapURL': sourceMapURL
};
source = fs.readFileSync(filePath, 'utf8');
}
modes = options.modes || modes;
if (options.isMapped) {
modes = modes.filter(function(mode) {
return mode != 'hybrid';
});
}
if (options.isTemplate) {
modes = modes.filter(function(mode) {
return mode != 'advanced';
});
}
options.modes = modes;
// fetch the Closure Compiler
getDependency({
'id': 'closure-compiler',
'hashId': closureId,
'path': vendorPath,
'title': 'the Closure Compiler',
'onComplete': function(exception) {
var error = exception;
// fetch UglifyJS
getDependency({
'id': 'uglifyjs',
'hashId': uglifyId,
'title': 'UglifyJS',
'path': vendorPath,
'onComplete': function(exception) {
error || (error = exception);
if (!error) {
new Minify(source, options);
}
}
});
}
});
}
/**
* The Minify constructor used to keep state of each `minify` invocation.
*
* @private
* @constructor
* @param {String} source The source to minify.
* @param {Object} options The options object.
* outputPath - Write output to a given path/filename.
* isSilent - Skip status updates normally logged to the console.
* isTemplate - Applies template specific minifier options.
* onComplete - The function called once minification has finished.
*/
function Minify(source, options) {
// juggle arguments
if (typeof source == 'object' && source) {
options = source || options;
source = options.source || '';
}
this.compiled = { 'simple': {}, 'advanced': {} };
this.hybrid = { 'simple': {}, 'advanced': {} };
this.uglified = {};
this.filePath = options.filePath;
this.isMapped = !!options.isMapped;
this.isSilent = !!options.isSilent;
this.isTemplate = !!options.isTemplate;
this.outputPath = options.outputPath;
this.sourceMapURL = options.sourceMapURL;
var modes = this.modes = options.modes;
source = this.source = preprocess(source, options);
this.onComplete = options.onComplete || function(data) {
var outputPath = this.outputPath,
sourceMap = data.sourceMap;
fs.writeFileSync(outputPath, data.source, 'utf8');
if (sourceMap) {
fs.writeFileSync(getMapPath(outputPath), sourceMap, 'utf8');
}
};
// begin the minification process
if (modes.indexOf('simple') > -1) {
closureCompile.call(this, source, 'simple', onClosureSimpleCompile.bind(this));
} else if (modes.indexOf('advanced') > -1) {
onClosureSimpleGzip.call(this);
} else {
onClosureAdvancedGzip.call(this);
}
}
/*--------------------------------------------------------------------------*/
/**
* Fetches a required `.tar.gz` dependency with the given Git object ID from
* the Lo-Dash repo on GitHub. The object ID may be obtained by running
* `git hash-object path/to/dependency.tar.gz`.
*
* @private
* @param {Object} options The options object.
* id - The Git object ID of the `.tar.gz` file.
* onComplete - The function called once the extraction has finished.
* path - The path of the extraction directory.
* title - The dependency's title used in status updates logged to the console.
*/
function getDependency(options) {
options || (options = {});
var ran,
destPath = options.path,
hashId = options.hashId,
id = options.id,
onComplete = options.onComplete,
title = options.title;
// exit early if dependency exists
if (fs.existsSync(path.join(destPath, id))) {
onComplete();
return;
}
var callback = function(exception) {
if (ran) {
return;
}
if (exception) {
console.error([
'There was a problem installing ' + title + '.',
'Try running the command as root, via `sudo`, or manually install by running:',
'',
"curl -H 'Accept: " + mediaType + "' " + location.href + '/' + hashId + " | tar xvz -C '" + destPath + "'",
''
].join('\n'));
}
ran = true;
process.removeListener('uncaughtException', callback);
onComplete(exception);
};
console.log('Downloading ' + title + '...');
process.on('uncaughtException', callback);
https.get({
'host': location.host,
'path': location.pathname + '/' + hashId,
'headers': {
// By default, all GitHub blob API endpoints return a JSON document
// containing Base64-encoded blob data. Overriding the `Accept` header
// with the GitHub raw media type returns the blob data directly.
// See http://developer.github.com/v3/media/.
'Accept': mediaType
}
}, function(response) {
var decompressor = zlib.createUnzip(),
parser = new tar.Extract({ 'path': destPath });
parser.on('end', callback);
response.pipe(decompressor).pipe(parser);
});
}
/**
* Resolves the source map path from the given output path.
*
* @private
* @param {String} outputPath The output path.
* @returns {String} Returns the source map path.
*/
function getMapPath(outputPath) {
return path.join(path.dirname(outputPath), path.basename(outputPath, '.js') + '.map');
}
/*--------------------------------------------------------------------------*/
/**
* Compresses a `source` string using the Closure Compiler. Yields the
* minified result, and any exceptions encountered, to a `callback` function.
*
* @private
* @param {String} source The JavaScript source to minify.
* @param {String} mode The optimization mode.
* @param {Function} callback The function called once the process has completed.
*/
function closureCompile(source, mode, callback) {
var filePath = this.filePath,
isAdvanced = mode == 'advanced',
isMapped = this.isMapped,
options = closureOptions.slice(),
outputPath = this.outputPath,
mapPath = getMapPath(outputPath),
sourceMapURL = this.sourceMapURL || path.basename(mapPath);
// remove copyright header to make other modifications easier
var license = (/^(?:\s*\/\/.*\s*|\s*\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/\s*)*/.exec(source) || [''])[0];
if (license) {
source = source.replace(license, '');
}
var hasIIFE = /^;?\(function[^{]+{\s*/.test(source),
isStrict = hasIIFE && /^;?\(function[^{]+{\s*["']use strict["']/.test(source);
// to avoid stripping the IIFE, convert it to a function call
if (hasIIFE && isAdvanced) {
source = source
.replace(/\(function/, '__iife__$&')
.replace(/\(this\)\)([\s;]*(\n\/\/.+)?)$/, ', this)$1');
}
options.push('--compilation_level=' + optimizationModes[mode]);
if (isMapped) {
options.push('--create_source_map=' + mapPath, '--source_map_format=V3');
}
var compiler = spawn('java', ['-jar', closurePath].concat(options));
if (!this.isSilent) {
console.log('Compressing ' + path.basename(outputPath, '.js') + ' using the Closure Compiler (' + mode + ')...');
}
var error = '';
compiler.stderr.on('data', function(data) {
error += data;
});
var output = '';
compiler.stdout.on('data', function(data) {
output += data;
});
compiler.on('exit', function(status) {
// `status` contains the process exit code
if (status) {
var exception = new Error(error);
exception.status = status;
}
// restore IIFE and move exposed vars inside the IIFE
if (hasIIFE && isAdvanced) {
output = output
.replace(/__iife__\(/, '(')
.replace(/,\s*this\)([\s;]*(\n\/\/.+)?)$/, '(this))$1')
.replace(/^((?:var (?:\w+=(?:!0|!1|null)[,;])+)?)([\s\S]*?function[^{]+{)/, '$2$1');
}
// inject "use strict" directive
if (isStrict) {
output = output.replace(/^[\s\S]*?function[^{]+{/, '$&"use strict";');
}
// restore copyright header
if (license) {
output = license + output;
}
if (isMapped) {
var mapOutput = fs.readFileSync(mapPath, 'utf8');
fs.unlinkSync(mapPath);
output = output.replace(/[\s;]*$/, '\n/*\n//@ sourceMappingURL=' + sourceMapURL) + '\n*/';
mapOutput = JSON.parse(mapOutput);
mapOutput.file = path.basename(outputPath);
mapOutput.sources = [path.basename(filePath)];
mapOutput = JSON.stringify(mapOutput, null, 2);
}
callback(exception, output, mapOutput);
});
// proxy the standard input to the Closure Compiler
compiler.stdin.end(source);
}
/**
* Compresses a `source` string using UglifyJS. Yields the result to a
* `callback` function. This function is synchronous; the `callback` is used
* for symmetry.
*
* @private
* @param {String} source The JavaScript source to minify.
* @param {String} label The label to log.
* @param {Function} callback The function called once the process has completed.
*/
function uglify(source, label, callback) {
if (!this.isSilent) {
console.log('Compressing ' + path.basename(this.outputPath, '.js') + ' using ' + label + '...');
}
try {
var uglifyJS = require(uglifyPath);
// 1. parse
var toplevel = uglifyJS.parse(source);
// 2. compress
// enable unsafe comparisons
toplevel.figure_out_scope();
toplevel = toplevel.transform(uglifyJS.Compressor({
'comparisons': false,
'unsafe_comps': true,
'warnings': false
}));
// 3. mangle
// excluding the `define` function exposed by AMD loaders
toplevel.figure_out_scope();
toplevel.compute_char_frequency();
toplevel.mangle_names({
'except': ['define']
});
// 4. output
// restrict lines to 500 characters for consistency with the Closure Compiler
var stream = uglifyJS.OutputStream({
'ascii_only': true,
'comments': /@cc_on|@license|@preserve/i,
'max_line_len': 500,
});
toplevel.print(stream);
}
catch(e) {
var exception = e;
}
callback(exception, stream && String(stream));
}
/*--------------------------------------------------------------------------*/
/**
* The Closure Compiler callback for simple optimizations.
*
* @private
* @param {Object|Undefined} exception The error object.
* @param {String} result The resulting minified source.
* @param {String} map The source map output.
*/
function onClosureSimpleCompile(exception, result, map) {
if (exception) {
throw exception;
}
result = postprocess(result);
var simple = this.compiled.simple;
simple.source = result;
simple.sourceMap = map;
zlib.gzip(result, onClosureSimpleGzip.bind(this));
}
/**
* The Closure Compiler `gzip` callback for simple optimizations.
*
* @private
* @param {Object|Undefined} exception The error object.
* @param {Buffer} result The resulting gzipped source.
*/
function onClosureSimpleGzip(exception, result) {
if (exception) {
throw exception;
}
if (result != null) {
if (!this.isSilent) {
console.log('Done. Size: %d bytes.', result.length);
}
this.compiled.simple.gzip = result;
}
// compile the source using advanced optimizations
if (this.modes.indexOf('advanced') > -1) {
closureCompile.call(this, this.source, 'advanced', onClosureAdvancedCompile.bind(this));
} else {
onClosureAdvancedGzip.call(this);
}
}
/**
* The Closure Compiler callback for advanced optimizations.
*
* @private
* @param {Object|Undefined} exception The error object.
* @param {String} result The resulting minified source.
* @param {String} map The source map output.
*/
function onClosureAdvancedCompile(exception, result, map) {
if (exception) {
throw exception;
}
result = postprocess(result);
var advanced = this.compiled.advanced;
advanced.source = result;
advanced.sourceMap = map;
zlib.gzip(result, onClosureAdvancedGzip.bind(this));
}
/**
* The Closure Compiler `gzip` callback for advanced optimizations.
*
* @private
* @param {Object|Undefined} exception The error object.
* @param {Buffer} result The resulting gzipped source.
*/
function onClosureAdvancedGzip(exception, result) {
if (exception) {
throw exception;
}
if (result != null) {
if (!this.isSilent) {
console.log('Done. Size: %d bytes.', result.length);
}
this.compiled.advanced.gzip = result;
}
// minify the source using UglifyJS
if (!this.isMapped) {
uglify.call(this, this.source, 'UglifyJS', onUglify.bind(this));
} else {
onComplete.call(this);
}
}
/**
* The UglifyJS callback.
*
* @private
* @param {Object|Undefined} exception The error object.
* @param {String} result The resulting minified source.
*/
function onUglify(exception, result) {
if (exception) {
throw exception;
}
result = postprocess(result);
this.uglified.source = result;
zlib.gzip(result, onUglifyGzip.bind(this));
}
/**
* The UglifyJS `gzip` callback.
*
* @private
* @param {Object|Undefined} exception The error object.
* @param {Buffer} result The resulting gzipped source.
*/
function onUglifyGzip(exception, result) {
if (exception) {
throw exception;
}
if (result != null) {
if (!this.isSilent) {
console.log('Done. Size: %d bytes.', result.length);
}
this.uglified.gzip = result;
}
// minify the already Closure Compiler simple optimized source using UglifyJS
var modes = this.modes;
if (modes.indexOf('hybrid') > -1) {
if (modes.indexOf('simple') > -1) {
uglify.call(this, this.compiled.simple.source, 'hybrid (simple)', onSimpleHybrid.bind(this));
} else if (modes.indexOf('advanced') > -1) {
onSimpleHybridGzip.call(this);
}
} else {
onComplete.call(this);
}
}
/**
* The hybrid callback for simple optimizations.
*
* @private
* @param {Object|Undefined} exception The error object.
* @param {String} result The resulting minified source.
*/
function onSimpleHybrid(exception, result) {
if (exception) {
throw exception;
}
result = postprocess(result);
this.hybrid.simple.source = result;
zlib.gzip(result, onSimpleHybridGzip.bind(this));
}
/**
* The hybrid `gzip` callback for simple optimizations.
*
* @private
* @param {Object|Undefined} exception The error object.
* @param {Buffer} result The resulting gzipped source.
*/
function onSimpleHybridGzip(exception, result) {
if (exception) {
throw exception;
}
if (result != null) {
if (!this.isSilent) {
console.log('Done. Size: %d bytes.', result.length);
}
this.hybrid.simple.gzip = result;
}
// minify the already Closure Compiler advance optimized source using UglifyJS
if (this.modes.indexOf('advanced') > -1) {
uglify.call(this, this.compiled.advanced.source, 'hybrid (advanced)', onAdvancedHybrid.bind(this));
} else {
onComplete.call(this);
}
}
/**
* The hybrid callback for advanced optimizations.
*
* @private
* @param {Object|Undefined} exception The error object.
* @param {String} result The resulting minified source.
*/
function onAdvancedHybrid(exception, result) {
if (exception) {
throw exception;
}
result = postprocess(result);
this.hybrid.advanced.source = result;
zlib.gzip(result, onAdvancedHybridGzip.bind(this));
}
/**
* The hybrid `gzip` callback for advanced optimizations.
*
* @private
* @param {Object|Undefined} exception The error object.
* @param {Buffer} result The resulting gzipped source.
*/
function onAdvancedHybridGzip(exception, result) {
if (exception) {
throw exception;
}
if (result != null) {
if (!this.isSilent) {
console.log('Done. Size: %d bytes.', result.length);
}
this.hybrid.advanced.gzip = result;
}
// finish by choosing the smallest compressed file
onComplete.call(this);
}
/**
* The callback executed after the source is minified and gzipped.
*
* @private
*/
function onComplete() {
var compiledSimple = this.compiled.simple,
compiledAdvanced = this.compiled.advanced,
uglified = this.uglified,
hybridSimple = this.hybrid.simple,
hybridAdvanced = this.hybrid.advanced;
var objects = [
compiledSimple,
compiledAdvanced,
uglified,
hybridSimple,
hybridAdvanced
];
var gzips = objects
.map(function(data) { return data.gzip; })
.filter(Boolean);
// select the smallest gzipped file and use its minified counterpart as the
// official minified release (ties go to the Closure Compiler)
var min = gzips.reduce(function(min, gzip) {
var length = gzip.length;
return min > length ? length : min;
}, Infinity);
// pass the minified source to the "onComplete" callback
objects.some(function(data) {
var gzip = data.gzip;
if (gzip && gzip.length == min) {
data.outputPath = this.outputPath;
this.onComplete(data);
return true;
}
}, this);
}
/*--------------------------------------------------------------------------*/
// expose `minify`
if (module != require.main) {
module.exports = minify;
}
else {
// 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
// `<filename>.min.js`
(function() {
var options = process.argv;
if (options.length < 3) {
return;
}
minify(options);
}());
}
}());

79
build/post-compile.js Normal file
View File

@@ -0,0 +1,79 @@
#!/usr/bin/env node
;(function() {
'use strict';
/** The Node filesystem module */
var fs = require('fs');
/** The minimal license/copyright template */
var licenseTemplate = [
'/**',
' * @license',
' * Lo-Dash <%= VERSION %> lodash.com/license',
' * Underscore.js 1.4.4 underscorejs.org/LICENSE',
' */'
].join('\n');
/*--------------------------------------------------------------------------*/
/**
* Post-process a given minified Lo-Dash `source`, preparing it for
* deployment.
*
* @param {String} source The source to process.
* @returns {String} Returns the processed source.
*/
function postprocess(source) {
// remove copyright header
source = source.replace(/^\/\**[\s\S]+?\*\/\n/, '');
// correct overly aggressive Closure Compiler advanced optimizations
source = source
.replace(/prototype\s*=\s*{\s*valueOf\s*:\s*1\s*}/, 'prototype={valueOf:1,y:1}')
.replace(/(document[^&]+&&)\s*(?:\w+|!\d)/, '$1!({toString:0}+"")');
// flip `typeof` expressions to help optimize Safari and
// correct the AMD module definition for AMD build optimizers
// (e.g. from `"number" == typeof x` to `typeof x == "number")
source = source.replace(/(\w)?("[^"]+")\s*([!=]=)\s*(typeof(?:\s*\([^)]+\)|\s+[.\w]+(?!\[)))/g, function(match, other, type, equality, expression) {
return (other ? other + ' ' : '') + expression + equality + type;
});
// add trailing semicolon
if (source) {
source = source.replace(/[\s;]*?(\s*\/\/.*\s*|\s*\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/\s*)*$/, ';$1');
}
// exit early if version snippet isn't found
var snippet = /VERSION\s*[=:]\s*([\'"])(.*?)\1/.exec(source);
if (!snippet) {
return source;
}
// add new copyright header
var version = snippet[2];
source = licenseTemplate.replace('<%= VERSION %>', version) + '\n;' + source;
return source;
}
/*--------------------------------------------------------------------------*/
// expose `postprocess`
if (module != require.main) {
module.exports = postprocess;
}
else {
// 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() {
var options = process.argv;
if (options.length < 3) {
return;
}
var filePath = options[options.length - 1],
source = fs.readFileSync(filePath, 'utf8');
fs.writeFileSync(filePath, postprocess(source), 'utf8');
}());
}
}());

382
build/pre-compile.js Normal file
View File

@@ -0,0 +1,382 @@
#!/usr/bin/env node
;(function() {
'use strict';
/** The Node filesystem module */
var fs = require('fs');
/** Used to minify variables embedded in compiled strings */
var compiledVars = [
'args',
'argsIndex',
'argsLength',
'callback',
'collection',
'createCallback',
'ctor',
'guard',
'hasOwnProperty',
'index',
'isArguments',
'isArray',
'isString',
'iterable',
'length',
'nativeKeys',
'object',
'objectTypes',
'ownIndex',
'ownProps',
'result',
'skipProto',
'source',
'thisArg'
];
/** Used to minify `compileIterator` option properties */
var iteratorOptions = [
'args',
'arrays',
'bottom',
'firstArg',
'hasDontEnumBug',
'hasEnumPrototype',
'isKeysFast',
'loop',
'nonEnumArgs',
'noCharByIndex',
'shadowed',
'top',
'useHas'
];
/** Used to minify variables and string values to a single character */
var minNames = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
minNames.push.apply(minNames, minNames.map(function(value) {
return value + value;
}));
/** Used to protect the specified properties from getting minified */
var propWhitelist = [
'_',
'__wrapped__',
'after',
'all',
'amd',
'any',
'assign',
'at',
'attachEvent',
'bind',
'bindAll',
'bindKey',
'clearTimeout',
'clone',
'cloneDeep',
'collect',
'compact',
'compose',
'contains',
'countBy',
'criteria',
'debounce',
'defaults',
'defer',
'delay',
'detect',
'difference',
'drop',
'each',
'environment',
'escape',
'evaluate',
'every',
'exports',
'extend',
'filter',
'find',
'first',
'flatten',
'foldl',
'foldr',
'forEach',
'forIn',
'forOwn',
'functions',
'global',
'groupBy',
'has',
'head',
'imports',
'identity',
'include',
'index',
'indexOf',
'initial',
'inject',
'interpolate',
'intersection',
'invert',
'invoke',
'isArguments',
'isArray',
'isBoolean',
'isDate',
'isElement',
'isEmpty',
'isEqual',
'isEqual',
'isFinite',
'isFinite',
'isFunction',
'isNaN',
'isNull',
'isNumber',
'isObject',
'isPlainObject',
'isRegExp',
'isString',
'isUndefined',
'keys',
'last',
'lastIndexOf',
'map',
'max',
'memoize',
'merge',
'methods',
'min',
'mixin',
'noConflict',
'object',
'omit',
'once',
'opera',
'pairs',
'partial',
'partialRight',
'pick',
'pluck',
'random',
'range',
'reduce',
'reduceRight',
'reject',
'rest',
'result',
'select',
'setImmediate',
'setTimeout',
'shuffle',
'size',
'some',
'sortBy',
'sortedIndex',
'source',
'tail',
'take',
'tap',
'template',
'templateSettings',
'throttle',
'times',
'toArray',
'unescape',
'union',
'uniq',
'unique',
'uniqueId',
'value',
'values',
'variable',
'VERSION',
'where',
'without',
'wrap',
'zip',
// properties used by the `backbone` and `underscore` builds
'__chain__',
'chain',
'findWhere'
];
/*--------------------------------------------------------------------------*/
/**
* Pre-process a given Lo-Dash `source`, preparing it for minification.
*
* @param {String} [source=''] The source to process.
* @param {Object} [options={}] The options object.
* @returns {String} Returns the processed source.
*/
function preprocess(source, options) {
source || (source = '');
options || (options = {});
// remove unrecognized JSDoc tags so the Closure Compiler won't complain
source = source.replace(/@(?:alias|category)\b.*/g, '');
if (options.isTemplate) {
return source;
}
// add brackets to whitelisted properties so the Closure Compiler won't mung them
// http://code.google.com/closure/compiler/docs/api-tutorial3.html#export
source = source.replace(RegExp('\\.(' + propWhitelist.join('|') + ')\\b', 'g'), function(match, prop) {
return "['" + prop.replace(/['\n\r\t]/g, '\\$&') + "']";
});
// remove brackets from `_.escape()` in `_.template`
source = source.replace(/__e *= *_\['escape']/g, '__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(/^([ "'\w]+:)? *"[^"\\\n]*(?:\\.[^"\\\n]*)*"|'[^'\\\n]*(?:\\.[^'\\\n]*)*'/gm, function(string, captured) {
// remove object literal property name
if (/:$/.test(captured)) {
string = string.slice(captured.length);
}
// avoids removing the '\n' of the `stringEscapes` object
string = string.replace(/\[object |delete |else (?!{)|function | in |return\s+[\w"']|throw |typeof |use strict|var |@ |(["'])\\n\1|\\\\n|\\n|\s+/g, function(match) {
return match == false || match == '\\n' ? '' : match;
});
// prepend object literal property name
return (captured || '') + string;
});
// remove whitespace from `_.template` related regexes
source = source.replace(/reEmptyString\w+ *=.+/g, function(match) {
return match.replace(/ |\\n/g, '');
});
// remove newline from double-quoted strings in `_.template`
source = source
.replace('"__p += \'"', '"__p+=\'"')
.replace('"\';\n"', '"\';"')
// remove debug sourceURL use in `_.template`
source = source.replace(/(?:\s*\/\/.*\n)* *var sourceURL[^;]+;|\+ *sourceURL/g, '');
// minify internal properties used by 'compareAscending' and `_.sortBy`
(function() {
var properties = ['criteria', 'index', 'value'],
snippets = source.match(/( +)function (?:compareAscending|sortBy)\b[\s\S]+?\n\1}/g);
if (!snippets) {
return;
}
snippets.forEach(function(snippet) {
var modified = snippet;
// minify properties
properties.forEach(function(property, index) {
var minName = minNames[index],
reBracketProp = RegExp("\\['(" + property + ")'\\]", 'g'),
reDotProp = RegExp('\\.' + property + '\\b', 'g'),
rePropColon = RegExp("([^?\\s])\\s*([\"'])?\\b" + property + "\\2 *:", 'g');
modified = modified
.replace(reBracketProp, "['" + minName + "']")
.replace(reDotProp, "['" + minName + "']")
.replace(rePropColon, "$1'" + minName + "':");
});
// replace with modified snippet
source = source.replace(snippet, modified);
});
}());
// minify all compilable snippets
var snippets = source.match(
RegExp([
// match the `iteratorTemplate`
'( +)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\\2}',
// match the the `createIterator` function
'( +)function createIterator\\b[\\s\\S]+?\\n\\3}'
].join('|'), 'g')
);
// exit early if no compilable snippets
if (!snippets) {
return source;
}
snippets.forEach(function(snippet, index) {
var isCreateIterator = /function createIterator\b/.test(snippet),
isIteratorTemplate = /var iteratorTemplate\b/.test(snippet),
modified = snippet;
// add brackets to iterator option properties so the Closure Compiler won't mung them
modified = modified.replace(RegExp('\\.(' + iteratorOptions.join('|') + ')\\b', 'g'), function(match, prop) {
return "['" + prop.replace(/['\n\r\t]/g, '\\$&') + "']";
});
if (isCreateIterator) {
// clip before the `factory` call to avoid minifying its arguments
source = source.replace(snippet, modified);
snippet = modified = modified.replace(/return factory\([\s\S]+$/, '');
}
// minify `createIterator` option property names
iteratorOptions.forEach(function(property, index) {
var minName = minNames[index];
// minify variables in `iteratorTemplate` or property names in everything else
modified = isIteratorTemplate
? modified.replace(RegExp('\\b' + property + '\\b', 'g'), minName)
: modified.replace(RegExp("'" + property + "'", 'g'), "'" + minName + "'");
});
// minify snippet variables / arguments
compiledVars.forEach(function(variable, index) {
var minName = minNames[index];
// ensure properties in compiled strings aren't minified
modified = modified.replace(RegExp('([^.]\\b)' + variable + '\\b(?!\' *[\\]:])', 'g'), '$1' + minName);
// correct `typeof` values
if (/^(?:boolean|function|object|number|string|undefined)$/.test(variable)) {
modified = modified.replace(RegExp("(typeof [^']+')" + minName + "'", 'g'), '$1' + variable + "'");
}
});
// replace with modified snippet
source = source.replace(snippet, modified);
});
return source;
}
/*--------------------------------------------------------------------------*/
// expose `preprocess`
if (module != require.main) {
module.exports = preprocess;
}
else {
// 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() {
var options = process.argv;
if (options.length < 3) {
return;
}
var filePath = options[options.length - 1],
isTemplate = options.indexOf('-t') > -1 || options.indexOf('--template') > -1,
source = fs.readFileSync(filePath, 'utf8');
fs.writeFileSync(filePath, preprocess(source, {
'isTemplate': isTemplate
}), 'utf8');
}());
}
}());

View File

@@ -1,10 +0,0 @@
{
"name": "lodash",
"repo": "lodash/lodash",
"version": "3.7.0",
"description": "The modern build of lodash.",
"license": "MIT",
"main": "lodash.js",
"keywords": ["stdlib", "util"],
"scripts": ["lodash.js"]
}

5152
dist/lodash.compat.js vendored Normal file

File diff suppressed because it is too large Load Diff

42
dist/lodash.compat.min.js vendored Normal file
View File

@@ -0,0 +1,42 @@
/**
* @license
* Lo-Dash 1.0.2 (Custom Build) lodash.com/license
* Build: `lodash -o ./dist/lodash.compat.js`
* Underscore.js 1.4.4 underscorejs.org/LICENSE
*/
;(function(n,t){function r(n){return n&&typeof n=="object"&&n.__wrapped__?n:this instanceof r?(this.__wrapped__=n,void 0):new r(n)}function e(n,t,r){t||(t=0);var e=n.length,u=e-t>=(r||at);if(u){var o={};for(r=t-1;++r<e;){var i=n[r]+"";(St.call(o,i)?o[i]:o[i]=[]).push(n[r])}}return function(r){if(u){var e=r+"";return St.call(o,e)&&-1<z(o[e],r)}return-1<z(n,r,t)}}function u(n){return n.charCodeAt(0)}function o(n,t){var r=n.b,e=t.b;if(n=n.a,t=t.a,n!==t){if(n>t||typeof n=="undefined")return 1;if(n<t||typeof t=="undefined")return-1
}return r<e?-1:1}function i(n,t,r,e){function u(){var a=arguments,c=i?this:t;return o||(n=t[f]),r.length&&(a=a.length?(a=v(a),e?a.concat(r):r.concat(a)):r),this instanceof u?(s.prototype=n.prototype,c=new s,s.prototype=W,a=n.apply(c,a),x(a)?a:c):n.apply(c,a)}var o=w(n),i=!r,f=t;return i&&(r=t),o||(t=n),u}function f(n,t,r){if(n==W)return G;var e=typeof n;if("function"!=e){if("object"!=e)return function(t){return t[n]};var u=vr(n);return function(t){for(var r=u.length,e=X;r--&&(e=j(t[u[r]],n[u[r]],ft)););return e
}}return typeof t!="undefined"?1===r?function(r){return n.call(t,r)}:2===r?function(r,e){return n.call(t,r,e)}:4===r?function(r,e,u,o){return n.call(t,r,e,u,o)}:function(r,e,u){return n.call(t,r,e,u)}:n}function a(){for(var n,t={e:tt,f:rt,g:Jt,i:Wt,j:Zt,k:jt,b:"l(n)",c:"",h:"",l:"",m:Q},r=0;n=arguments[r];r++)for(var e in n)t[e]=n[e];if(n=t.a,t.d=/^[^,]+/.exec(n)[0],r="var j,n="+t.d+",u=n;if(!n)return u;"+t.l+";",t.b?(r+="var o=n.length;j=-1;if("+t.b+"){",t.j&&(r+="if(m(n)){n=n.split('')}"),r+="while(++j<o){"+t.h+"}}else{"):t.i&&(r+="var o=n.length;j=-1;if(o&&k(n)){while(++j<o){j+='';"+t.h+"}}else{"),t.f&&(r+="var v=typeof n=='function';"),t.g&&t.m?(r+="var s=-1,t=r[typeof n]?p(n):[],o=t.length;while(++s<o){j=t[s];",t.f&&(r+="if(!(v&&j=='prototype')){"),r+=t.h+"",t.f&&(r+="}")):(r+="for(j in n){",(t.f||t.m)&&(r+="if(",t.f&&(r+="!(v&&j=='prototype')"),t.f&&t.m&&(r+="&&"),t.m&&(r+="i.call(n,j)"),r+="){"),r+=t.h+";",(t.f||t.m)&&(r+="}")),r+="}",t.e)for(r+="var g=n.constructor;",e=0;7>e;e++)r+="j='"+t.k[e]+"';if(","constructor"==t.k[e]&&(r+="!(g&&g.prototype===n)&&"),r+="i.call(n,j)){"+t.h+"}";
return(t.b||t.i)&&(r+="}"),r+=t.c+";return u",Function("f,i,k,l,m,r,p","return function("+n+"){"+r+"}")(f,St,y,sr,A,ur,Ft)}function c(n){return"\\"+or[n]}function l(n){return gr[n]}function p(n){return typeof n.toString!="function"&&typeof(n+"")=="string"}function s(){}function v(n,t,r){t||(t=0),typeof r=="undefined"&&(r=n?n.length:0);var e=-1;r=r-t||0;for(var u=Array(0>r?0:r);++e<r;)u[e]=n[t+e];return u}function g(n){return yr[n]}function y(n){return kt.call(n)==Bt}function h(n){var t=X;if(!n||typeof n!="object"||y(n))return t;
var r=n.constructor;return!w(r)&&(!nr||!p(n))||r instanceof r?et?(lr(n,function(n,r,e){return t=!St.call(e,r),X}),t===X):(lr(n,function(n,r){t=r}),t===X||St.call(n,t)):t}function m(n){var t=[];return pr(n,function(n,r){t.push(r)}),t}function d(n,r,e,u,o,i){var a=n;if(typeof r=="function"&&(u=e,e=r,r=X),typeof e=="function"){e=typeof u=="undefined"?e:f(e,u,1);var a=e(a),c=typeof a!="undefined";c||(a=n)}if(u=x(a)){var l=kt.call(a);if(!rr[l]||nr&&p(a))return a;var s=sr(a)}if(!u||!r)return u&&!c?s?v(a):hr({},a):a;
switch(u=er[l],l){case Pt:case zt:return c?a:new u(+a);case Ct:case Ut:return c?a:new u(a);case Lt:return c?a:u(a.source,gt.exec(a))}for(o||(o=[]),i||(i=[]),l=o.length;l--;)if(o[l]==n)return i[l];return c||(a=s?u(a.length):{},s&&(St.call(n,"index")&&(a.index=n.index),St.call(n,"input")&&(a.input=n.input))),o.push(n),i.push(a),(s?$:pr)(c?a:n,function(n,u){a[u]=d(n,r,e,t,o,i)}),a}function _(n){var t=[];return lr(n,function(n,r){w(n)&&t.push(r)}),t.sort()}function b(n){for(var t=-1,r=vr(n),e=r.length,u={};++t<e;){var o=r[t];
u[n[o]]=o}return u}function j(n,t,r,e,u,o){var i=r===ft;if(r&&!i){r=typeof e=="undefined"?r:f(r,e,2);var a=r(n,t);if(typeof a!="undefined")return!!a}if(n===t)return 0!==n||1/n==1/t;var c=typeof n,l=typeof t;if(n===n&&(!n||"function"!=c&&"object"!=c)&&(!t||"function"!=l&&"object"!=l))return X;if(n==W||t==W)return n===t;if(l=kt.call(n),c=kt.call(t),l==Bt&&(l=Kt),c==Bt&&(c=Kt),l!=c)return X;switch(l){case Pt:case zt:return+n==+t;case Ct:return n!=+n?t!=+t:0==n?1/n==1/t:n==+t;case Lt:case Ut:return n==t+""
}if(c=l==Mt,!c){if(n.__wrapped__||t.__wrapped__)return j(n.__wrapped__||n,t.__wrapped__||t,r,e,u,o);if(l!=Kt||nr&&(p(n)||p(t)))return X;var l=!Xt&&y(n)?Object:n.constructor,s=!Xt&&y(t)?Object:t.constructor;if(l!=s&&(!w(l)||!(l instanceof l&&w(s)&&s instanceof s)))return X}for(u||(u=[]),o||(o=[]),l=u.length;l--;)if(u[l]==n)return o[l]==t;var v=0,a=Q;if(u.push(n),o.push(t),c){if(l=n.length,v=t.length,a=v==n.length,!a&&!i)return a;for(;v--;)if(c=l,s=t[v],i)for(;c--&&!(a=j(n[c],s,r,e,u,o)););else if(!(a=j(n[v],s,r,e,u,o)))break;
return a}return lr(t,function(t,i,f){return St.call(f,i)?(v++,a=St.call(n,i)&&j(n[i],t,r,e,u,o)):void 0}),a&&!i&&lr(n,function(n,t,r){return St.call(r,t)?a=-1<--v:void 0}),a}function w(n){return typeof n=="function"}function x(n){return n?ur[typeof n]:X}function O(n){return typeof n=="number"||kt.call(n)==Ct}function A(n){return typeof n=="string"||kt.call(n)==Ut}function S(n,t,r){var e=arguments,u=0,o=2;if(!x(n))return n;if(r===ft)var i=e[3],a=e[4],c=e[5];else a=[],c=[],typeof r!="number"&&(o=e.length),3<o&&"function"==typeof e[o-2]?i=f(e[--o-1],e[o--],2):2<o&&"function"==typeof e[o-1]&&(i=e[--o]);
for(;++u<o;)(sr(e[u])?$:pr)(e[u],function(t,r){var e,u,o=t,f=n[r];if(t&&((u=sr(t))||dr(t))){for(o=a.length;o--;)if(e=a[o]==t){f=c[o];break}e||(f=u?sr(f)?f:[]:dr(f)?f:{},i&&(o=i(f,t),typeof o!="undefined"&&(f=o)),a.push(t),c.push(f),i||(f=S(f,t,ft,i,a,c)))}else i&&(o=i(f,t),typeof o=="undefined"&&(o=t)),typeof o!="undefined"&&(f=o);n[r]=f});return n}function E(n){for(var t=-1,r=vr(n),e=r.length,u=Array(e);++t<e;)u[t]=n[r[t]];return u}function k(n,t,r){var e=-1,u=n?n.length:0,o=X;return r=(0>r?qt(0,u+r):r)||0,typeof u=="number"?o=-1<(A(n)?n.indexOf(t,r):z(n,t,r)):cr(n,function(n){return++e<r?void 0:!(o=n===t)
}),o}function I(n,t,r){var e=Q;if(t=f(t,r),sr(n)){r=-1;for(var u=n.length;++r<u&&(e=!!t(n[r],r,n)););}else cr(n,function(n,r,u){return e=!!t(n,r,u)});return e}function N(n,t,r){var e=[];if(t=f(t,r),sr(n)){r=-1;for(var u=n.length;++r<u;){var o=n[r];t(o,r,n)&&e.push(o)}}else cr(n,function(n,r,u){t(n,r,u)&&e.push(n)});return e}function R(n,t,r){var e;return t=f(t,r),$(n,function(n,r,u){return t(n,r,u)?(e=n,X):void 0}),e}function $(n,t,r){if(t&&typeof r=="undefined"&&sr(n)){r=-1;for(var e=n.length;++r<e&&t(n[r],r,n)!==X;);}else cr(n,t,r);
return n}function F(n,t,r){var e=-1,u=n?n.length:0,o=Array(typeof u=="number"?u:0);if(t=f(t,r),sr(n))for(;++e<u;)o[e]=t(n[e],e,n);else cr(n,function(n,r,u){o[++e]=t(n,r,u)});return o}function q(n,t,r){var e=-1/0,o=e;if(!t&&sr(n)){r=-1;for(var i=n.length;++r<i;){var a=n[r];a>o&&(o=a)}}else t=!t&&A(n)?u:f(t,r),cr(n,function(n,r,u){r=t(n,r,u),r>e&&(e=r,o=n)});return o}function D(n,t,r,e){var u=3>arguments.length;if(t=f(t,e,4),sr(n)){var o=-1,i=n.length;for(u&&(r=n[++o]);++o<i;)r=t(r,n[o],o,n)}else cr(n,function(n,e,o){r=u?(u=X,n):t(r,n,e,o)
});return r}function T(n,t,r,e){var u=n,o=n?n.length:0,i=3>arguments.length;if(typeof o!="number")var a=vr(n),o=a.length;else Zt&&A(n)&&(u=n.split(""));return t=f(t,e,4),$(n,function(n,e,f){e=a?a[--o]:--o,r=i?(i=X,u[e]):t(r,u[e],e,f)}),r}function B(n,t,r){var e;if(t=f(t,r),sr(n)){r=-1;for(var u=n.length;++r<u&&!(e=t(n[r],r,n)););}else cr(n,function(n,r,u){return!(e=t(n,r,u))});return!!e}function M(n,t,r){if(n){var e=0,u=n.length;if(typeof t!="number"&&t!=W){var o=-1;for(t=f(t,r);++o<u&&t(n[o],o,n);)e++
}else if(e=t,e==W||r)return n[0];return v(n,0,Dt(qt(0,e),u))}}function P(n,t){for(var r=-1,e=n?n.length:0,u=[];++r<e;){var o=n[r];sr(o)?Et.apply(u,t?o:P(o)):u.push(o)}return u}function z(n,t,r){var e=-1,u=n?n.length:0;if(typeof r=="number")e=(0>r?qt(0,u+r):r||0)-1;else if(r)return e=K(n,t),n[e]===t?e:-1;for(;++e<u;)if(n[e]===t)return e;return-1}function C(n,t,r){if(typeof t!="number"&&t!=W){var e=0,u=-1,o=n?n.length:0;for(t=f(t,r);++u<o&&t(n[u],u,n);)e++}else e=t==W||r?1:qt(0,t);return v(n,e)}function K(n,t,r,e){var u=0,o=n?n.length:u;
for(r=r?f(r,e,1):G,t=r(t);u<o;)e=u+o>>>1,r(n[e])<t?u=e+1:o=e;return u}function L(n,t,r,e){var u=-1,o=n?n.length:0,i=[],a=i;typeof t=="function"&&(e=r,r=t,t=X);var c=!t&&75<=o;if(c)var l={};for(r&&(a=[],r=f(r,e));++u<o;){e=n[u];var p=r?r(e,u,n):e;if(c)var s=p+"",s=St.call(l,s)?!(a=l[s]):a=l[s]=[];(t?!u||a[a.length-1]!==p:s||0>z(a,p))&&((r||c)&&a.push(p),i.push(e))}return i}function U(n,t){return Ht||It&&2<arguments.length?It.call.apply(It,arguments):i(n,t,v(arguments,2))}function V(n){var r=v(arguments,1);
return setTimeout(function(){n.apply(t,r)},1)}function G(n){return n}function H(n){$(_(n),function(t){var e=r[t]=n[t];r.prototype[t]=function(){var n=[this.__wrapped__];return Et.apply(n,arguments),new r(e.apply(r,n))}})}function J(){return this.__wrapped__}var Q=!0,W=null,X=!1,Y=typeof exports=="object"&&exports,Z=typeof module=="object"&&module&&module.exports==Y&&module,nt=typeof global=="object"&&global;nt.global===nt&&(n=nt);var tt,rt,et,ut=[],ot={},it=0,ft=ot,at=30,ct=n._,lt=/&(?:amp|lt|gt|quot|#39);/g,pt=/\b__p\+='';/g,st=/\b(__p\+=)''\+/g,vt=/(__e\(.*?\)|\b__t\))\+'';/g,gt=/\w*$/,yt=RegExp("^"+(ot.valueOf+"").replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/valueOf|for [^\]]+/g,".+?")+"$"),ht=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,mt=/<%=([\s\S]+?)%>/g,dt=/($^)/,_t=/[&<>"']/g,bt=/['\n\r\t\u2028\u2029\\]/g,jt="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" "),wt=Math.ceil,xt=ut.concat,Ot=Math.floor,At=yt.test(At=Object.getPrototypeOf)&&At,St=ot.hasOwnProperty,Et=ut.push,kt=ot.toString,It=yt.test(It=v.bind)&&It,Nt=yt.test(Nt=Array.isArray)&&Nt,Rt=n.isFinite,$t=n.isNaN,Ft=yt.test(Ft=Object.keys)&&Ft,qt=Math.max,Dt=Math.min,Tt=Math.random,Bt="[object Arguments]",Mt="[object Array]",Pt="[object Boolean]",zt="[object Date]",Ct="[object Number]",Kt="[object Object]",Lt="[object RegExp]",Ut="[object String]",Vt=!!n.attachEvent,Gt=It&&!/\n|true/.test(It+Vt),Ht=It&&!Gt,Jt=Ft&&(Vt||Gt),Qt=(Qt={0:1,length:1},ut.splice.call(Qt,0,1),Qt[0]),Wt=Q;
(function(){function n(){this.x=1}var t=[];n.prototype={valueOf:1,y:1};for(var r in new n)t.push(r);for(r in arguments)Wt=!r;tt=!/valueOf/.test(t),rt=n.propertyIsEnumerable("prototype"),et="x"!=t[0]})(1);var Xt=arguments.constructor==Object,Yt=!y(arguments),Zt="xx"!="x"[0]+Object("x")[0];try{var nr=kt.call(document)==Kt&&!({toString:0}+"")}catch(tr){}var rr={"[object Function]":X};rr[Bt]=rr[Mt]=rr[Pt]=rr[zt]=rr[Ct]=rr[Kt]=rr[Lt]=rr[Ut]=Q;var er={};er[Mt]=Array,er[Pt]=Boolean,er[zt]=Date,er[Kt]=Object,er[Ct]=Number,er[Lt]=RegExp,er[Ut]=String;
var ur={"boolean":X,"function":Q,object:Q,number:X,string:X,undefined:X},or={"\\":"\\","'":"'","\n":"n","\r":"r"," ":"t","\u2028":"u2028","\u2029":"u2029"};r.templateSettings={escape:/<%-([\s\S]+?)%>/g,evaluate:/<%([\s\S]+?)%>/g,interpolate:mt,variable:"",imports:{_:r}};var ir={a:"q,w,h",l:"var a=arguments,b=0,c=typeof h=='number'?2:a.length;while(++b<c){n=a[b];if(n&&r[typeof n]){",h:"if(typeof u[j]=='undefined')u[j]=n[j]",c:"}}"},fr={a:"e,d,x",l:"d=d&&typeof x=='undefined'?d:f(d,x)",b:"typeof o=='number'",h:"if(d(n[j],j,e)===false)return u"},ar={l:"if(!r[typeof n])return u;"+fr.l,b:X},cr=a(fr);
Yt&&(y=function(n){return n?St.call(n,"callee"):X});var lr=a(fr,ar,{m:X}),pr=a(fr,ar),sr=Nt||function(n){return Xt&&n instanceof Array||kt.call(n)==Mt},vr=Ft?function(n){return x(n)?rt&&typeof n=="function"||Wt&&n.length&&y(n)?m(n):Ft(n):[]}:m,gr={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},yr=b(gr),hr=a(ir,{l:ir.l.replace(";",";if(c>3&&typeof a[c-2]=='function'){var d=f(a[--c-1],a[c--],2);}else if(c>2&&typeof a[c-1]=='function'){d=a[--c];}"),h:"u[j]=d?d(u[j],n[j]):n[j]"}),mr=a(ir);
w(/x/)&&(w=function(n){return n instanceof Function||"[object Function]"==kt.call(n)});var dr=At?function(n){if(!n||typeof n!="object")return X;var t=n.valueOf,r=typeof t=="function"&&(r=At(t))&&At(r);return r?n==r||At(n)==r&&!y(n):h(n)}:h,_r=F,br=N;Gt&&Z&&typeof setImmediate=="function"&&(V=U(setImmediate,n)),r.after=function(n,t){return 1>n?t():function(){return 1>--n?t.apply(this,arguments):void 0}},r.assign=hr,r.at=function(n){var t=-1,r=xt.apply(ut,v(arguments,1)),e=r.length,u=Array(e);for(Zt&&A(n)&&(n=n.split(""));++t<e;)u[t]=n[r[t]];
return u},r.bind=U,r.bindAll=function(n){for(var t=xt.apply(ut,arguments),r=1<t.length?0:(t=_(n),-1),e=t.length;++r<e;){var u=t[r];n[u]=U(n[u],n)}return n},r.bindKey=function(n,t){return i(n,t,v(arguments,2))},r.compact=function(n){for(var t=-1,r=n?n.length:0,e=[];++t<r;){var u=n[t];u&&e.push(u)}return e},r.compose=function(){var n=arguments;return function(){for(var t=arguments,r=n.length;r--;)t=[n[r].apply(this,t)];return t[0]}},r.countBy=function(n,t,r){var e={};return t=f(t,r),$(n,function(n,r,u){r=t(n,r,u)+"",St.call(e,r)?e[r]++:e[r]=1
}),e},r.debounce=function(n,t,r){function e(){f=W,r||(o=n.apply(i,u))}var u,o,i,f;return function(){var a=r&&!f;return u=arguments,i=this,clearTimeout(f),f=setTimeout(e,t),a&&(o=n.apply(i,u)),o}},r.defaults=mr,r.defer=V,r.delay=function(n,r){var e=v(arguments,2);return setTimeout(function(){n.apply(t,e)},r)},r.difference=function(n){for(var t=-1,r=n?n.length:0,u=xt.apply(ut,arguments),u=e(u,r),o=[];++t<r;){var i=n[t];u(i)||o.push(i)}return o},r.filter=N,r.flatten=P,r.forEach=$,r.forIn=lr,r.forOwn=pr,r.functions=_,r.groupBy=function(n,t,r){var e={};
return t=f(t,r),$(n,function(n,r,u){r=t(n,r,u)+"",(St.call(e,r)?e[r]:e[r]=[]).push(n)}),e},r.initial=function(n,t,r){if(!n)return[];var e=0,u=n.length;if(typeof t!="number"&&t!=W){var o=u;for(t=f(t,r);o--&&t(n[o],o,n);)e++}else e=t==W||r?1:t||e;return v(n,0,Dt(qt(0,u-e),u))},r.intersection=function(n){var t=arguments,r=t.length,u={0:{}},o=-1,i=n?n.length:0,f=100<=i,a=[],c=a;n:for(;++o<i;){var l=n[o];if(f)var p=l+"",p=St.call(u[0],p)?!(c=u[0][p]):c=u[0][p]=[];if(p||0>z(c,l)){f&&c.push(l);for(var s=r;--s;)if(!(u[s]||(u[s]=e(t[s],0,100)))(l))continue n;
a.push(l)}}return a},r.invert=b,r.invoke=function(n,t){var r=v(arguments,2),e=-1,u=typeof t=="function",o=n?n.length:0,i=Array(typeof o=="number"?o:0);return $(n,function(n){i[++e]=(u?t:n[t]).apply(n,r)}),i},r.keys=vr,r.map=F,r.max=q,r.memoize=function(n,t){var r={};return function(){var e=(t?t.apply(this,arguments):arguments[0])+"";return St.call(r,e)?r[e]:r[e]=n.apply(this,arguments)}},r.merge=S,r.min=function(n,t,r){var e=1/0,o=e;if(!t&&sr(n)){r=-1;for(var i=n.length;++r<i;){var a=n[r];a<o&&(o=a)
}}else t=!t&&A(n)?u:f(t,r),cr(n,function(n,r,u){r=t(n,r,u),r<e&&(e=r,o=n)});return o},r.object=function(n,t){for(var r=-1,e=n?n.length:0,u={};++r<e;){var o=n[r];t?u[o]=t[r]:u[o[0]]=o[1]}return u},r.omit=function(n,t,r){var e=typeof t=="function",u={};if(e)t=f(t,r);else var o=xt.apply(ut,arguments);return lr(n,function(n,r,i){(e?!t(n,r,i):0>z(o,r,1))&&(u[r]=n)}),u},r.once=function(n){var t,r;return function(){return t?r:(t=Q,r=n.apply(this,arguments),n=W,r)}},r.pairs=function(n){for(var t=-1,r=vr(n),e=r.length,u=Array(e);++t<e;){var o=r[t];
u[t]=[o,n[o]]}return u},r.partial=function(n){return i(n,v(arguments,1))},r.partialRight=function(n){return i(n,v(arguments,1),W,ft)},r.pick=function(n,t,r){var e={};if(typeof t!="function")for(var u=0,o=xt.apply(ut,arguments),i=x(n)?o.length:0;++u<i;){var a=o[u];a in n&&(e[a]=n[a])}else t=f(t,r),lr(n,function(n,r,u){t(n,r,u)&&(e[r]=n)});return e},r.pluck=_r,r.range=function(n,t,r){n=+n||0,r=+r||1,t==W&&(t=n,n=0);var e=-1;t=qt(0,wt((t-n)/r));for(var u=Array(t);++e<t;)u[e]=n,n+=r;return u},r.reject=function(n,t,r){return t=f(t,r),N(n,function(n,r,e){return!t(n,r,e)
})},r.rest=C,r.shuffle=function(n){var t=-1,r=n?n.length:0,e=Array(typeof r=="number"?r:0);return $(n,function(n){var r=Ot(Tt()*(++t+1));e[t]=e[r],e[r]=n}),e},r.sortBy=function(n,t,r){var e=-1,u=n?n.length:0,i=Array(typeof u=="number"?u:0);for(t=f(t,r),$(n,function(n,r,u){i[++e]={a:t(n,r,u),b:e,c:n}}),u=i.length,i.sort(o);u--;)i[u]=i[u].c;return i},r.tap=function(n,t){return t(n),n},r.throttle=function(n,t){function r(){f=new Date,i=W,u=n.apply(o,e)}var e,u,o,i,f=0;return function(){var a=new Date,c=t-(a-f);
return e=arguments,o=this,0<c?i||(i=setTimeout(r,c)):(clearTimeout(i),i=W,f=a,u=n.apply(o,e)),u}},r.times=function(n,t,r){n=+n||0;for(var e=-1,u=Array(n);++e<n;)u[e]=t.call(r,e);return u},r.toArray=function(n){return n&&typeof n.length=="number"?Zt&&A(n)?n.split(""):v(n):E(n)},r.union=function(){return L(xt.apply(ut,arguments))},r.uniq=L,r.values=E,r.where=br,r.without=function(n){for(var t=-1,r=n?n.length:0,u=e(arguments,1),o=[];++t<r;){var i=n[t];u(i)||o.push(i)}return o},r.wrap=function(n,t){return function(){var r=[n];
return Et.apply(r,arguments),t.apply(this,r)}},r.zip=function(n){for(var t=-1,r=n?q(_r(arguments,"length")):0,e=Array(r);++t<r;)e[t]=_r(arguments,t);return e},r.collect=F,r.drop=C,r.each=$,r.extend=hr,r.methods=_,r.select=N,r.tail=C,r.unique=L,H(r),r.clone=d,r.cloneDeep=function(n,t,r){return d(n,Q,t,r)},r.contains=k,r.escape=function(n){return n==W?"":(n+"").replace(_t,l)},r.every=I,r.find=R,r.has=function(n,t){return n?St.call(n,t):X},r.identity=G,r.indexOf=z,r.isArguments=y,r.isArray=sr,r.isBoolean=function(n){return n===Q||n===X||kt.call(n)==Pt
},r.isDate=function(n){return n instanceof Date||kt.call(n)==zt},r.isElement=function(n){return n?1===n.nodeType:X},r.isEmpty=function(n){var t=Q;if(!n)return t;var r=kt.call(n),e=n.length;return r==Mt||r==Ut||r==Bt||Yt&&y(n)||r==Kt&&typeof e=="number"&&w(n.splice)?!e:(pr(n,function(){return t=X}),t)},r.isEqual=j,r.isFinite=function(n){return Rt(n)&&!$t(parseFloat(n))},r.isFunction=w,r.isNaN=function(n){return O(n)&&n!=+n},r.isNull=function(n){return n===W},r.isNumber=O,r.isObject=x,r.isPlainObject=dr,r.isRegExp=function(n){return n instanceof RegExp||kt.call(n)==Lt
},r.isString=A,r.isUndefined=function(n){return typeof n=="undefined"},r.lastIndexOf=function(n,t,r){var e=n?n.length:0;for(typeof r=="number"&&(e=(0>r?qt(0,e+r):Dt(r,e-1))+1);e--;)if(n[e]===t)return e;return-1},r.mixin=H,r.noConflict=function(){return n._=ct,this},r.random=function(n,t){return n==W&&t==W&&(t=1),n=+n||0,t==W&&(t=n,n=0),n+Ot(Tt()*((+t||0)-n+1))},r.reduce=D,r.reduceRight=T,r.result=function(n,r){var e=n?n[r]:t;return w(e)?n[r]():e},r.size=function(n){var t=n?n.length:0;return typeof t=="number"?t:vr(n).length
},r.some=B,r.sortedIndex=K,r.template=function(n,e,u){var o=r.templateSettings;n||(n=""),u=mr({},u,o);var i,f=mr({},u.imports,o.imports),o=vr(f),f=E(f),a=0,l=u.interpolate||dt,p="__p+='";n.replace(RegExp((u.escape||dt).source+"|"+l.source+"|"+(l===mt?ht:dt).source+"|"+(u.evaluate||dt).source+"|$","g"),function(t,r,e,u,o,f){return e||(e=u),p+=n.slice(a,f).replace(bt,c),r&&(p+="'+__e("+r+")+'"),o&&(i=Q,p+="';"+o+";__p+='"),e&&(p+="'+((__t=("+e+"))==null?'':__t)+'"),a=f+t.length,t}),p+="';\n",l=u=u.variable,l||(u="obj",p="with("+u+"){"+p+"}"),p=(i?p.replace(pt,""):p).replace(st,"$1").replace(vt,"$1;"),p="function("+u+"){"+(l?"":u+"||("+u+"={});")+"var __t,__p='',__e=_.escape"+(i?",__j=Array.prototype.join;function print(){__p+=__j.call(arguments,'')}":";")+p+"return __p}";
try{var s=Function(o,"return "+p).apply(t,f)}catch(v){throw v.source=p,v}return e?s(e):(s.source=p,s)},r.unescape=function(n){return n==W?"":(n+"").replace(lt,g)},r.uniqueId=function(n){var t=++it;return(n==W?"":n+"")+t},r.all=I,r.any=B,r.detect=R,r.foldl=D,r.foldr=T,r.include=k,r.inject=D,pr(r,function(n,t){r.prototype[t]||(r.prototype[t]=function(){var t=[this.__wrapped__];return Et.apply(t,arguments),n.apply(r,t)})}),r.first=M,r.last=function(n,t,r){if(n){var e=0,u=n.length;if(typeof t!="number"&&t!=W){var o=u;
for(t=f(t,r);o--&&t(n[o],o,n);)e++}else if(e=t,e==W||r)return n[u-1];return v(n,qt(0,u-e))}},r.take=M,r.head=M,pr(r,function(n,t){r.prototype[t]||(r.prototype[t]=function(t,e){var u=n(this.__wrapped__,t,e);return t==W||e&&typeof t!="function"?u:new r(u)})}),r.VERSION="1.0.2",r.prototype.toString=function(){return this.__wrapped__+""},r.prototype.value=J,r.prototype.valueOf=J,cr(["join","pop","shift"],function(n){var t=ut[n];r.prototype[n]=function(){return t.apply(this.__wrapped__,arguments)}}),cr(["push","reverse","sort","unshift"],function(n){var t=ut[n];
r.prototype[n]=function(){return t.apply(this.__wrapped__,arguments),this}}),cr(["concat","slice","splice"],function(n){var t=ut[n];r.prototype[n]=function(){return new r(t.apply(this.__wrapped__,arguments))}}),Qt&&cr(["pop","shift","splice"],function(n){var t=ut[n],e="splice"==n;r.prototype[n]=function(){var n=this.__wrapped__,u=t.apply(n,arguments);return 0===n.length&&delete n[0],e?new r(u):u}}),typeof define=="function"&&typeof define.amd=="object"&&define.amd?(n._=r,define(function(){return r
})):Y?Z?(Z.exports=r)._=r:Y._=r:n._=r})(this);

4983
dist/lodash.js vendored Normal file

File diff suppressed because it is too large Load Diff

41
dist/lodash.min.js vendored Normal file
View File

@@ -0,0 +1,41 @@
/**
* @license
* Lo-Dash 1.0.2 (Custom Build) lodash.com/license
* Build: `lodash modern -o ./dist/lodash.js`
* Underscore.js 1.4.4 underscorejs.org/LICENSE
*/
;(function(n,r){function t(n){return n&&"object"==typeof n&&n.__wrapped__?n:this instanceof t?(this.__wrapped__=n,r):new t(n)}function e(n,r,t){r||(r=0);var e=n.length,u=e-r>=(t||ut);if(u)for(var a={},o=r-1;++o<e;){var i=n[o]+"";(wt.call(a,i)?a[i]:a[i]=[]).push(n[o])}return function(t){if(u){var e=t+"";return wt.call(a,e)&&sr(a[e],t)>-1}return sr(n,t,r)>-1}}function u(n){return n.charCodeAt(0)}function a(n,r){var t=n.index,e=r.index;if(n=n.criteria,r=r.criteria,n!==r){if(n>r||"undefined"==typeof n)return 1;
if(n<r||"undefined"==typeof r)return-1}return t<e?-1:1}function o(n,r,t,e){function u(){var f=arguments,l=o?this:r;if(a||(n=r[i]),t.length&&(f=f.length?(f=p(f),e?f.concat(t):t.concat(f)):t),this instanceof u){s.prototype=n.prototype,l=new s,s.prototype=null;var c=n.apply(l,f);return S(c)?c:l}return n.apply(l,f)}var a=E(n),o=!t,i=r;return o&&(t=r),a||(r=n),u}function i(n,r,t){if(null==n)return Br;var e=typeof n;if("function"!=e){if("object"!=e)return function(r){return r[n]};var u=ue(n);return function(r){for(var t=u.length,e=!1;t--&&(e=O(r[u[t]],n[u[t]],et)););return e
}}return"undefined"!=typeof r?1===t?function(t){return n.call(r,t)}:2===t?function(t,e){return n.call(r,t,e)}:4===t?function(t,e,u,a){return n.call(r,t,e,u,a)}:function(t,e,u){return n.call(r,t,e,u)}:n}function f(){for(var n,r={isKeysFast:Ut,arrays:"isArray(iterable)",bottom:"",loop:"",top:"",useHas:!0},t=0;n=arguments[t];t++)for(var e in n)r[e]=n[e];var u=r.args;r.firstArg=/^[^,]+/.exec(u)[0];var a=Function("createCallback, hasOwnProperty, isArguments, isArray, isString, objectTypes, nativeKeys","return function("+u+") {\n"+Wt(r)+"\n}");
return a(i,wt,v,ee,N,Jt,St)}function l(n){return"\\"+Qt[n]}function c(n){return ae[n]}function s(){}function p(n,r,t){r||(r=0),"undefined"==typeof t&&(t=n?n.length:0);for(var e=-1,u=t-r||0,a=Array(u<0?0:u);++e<u;)a[e]=n[r+e];return a}function g(n){return oe[n]}function v(n){return At.call(n)==Ft}function y(n){var r=!1;if(!n||"object"!=typeof n||v(n))return r;var t=n.constructor;return!E(t)||t instanceof t?(re(n,function(n,t){r=t}),r===!1||wt.call(n,r)):r}function h(n){var r=[];return te(n,function(n,t){r.push(t)
}),r}function d(n,t,e,u,a,o){var f=n;if("function"==typeof t&&(u=e,e=t,t=!1),"function"==typeof e){e="undefined"==typeof u?e:i(e,u,1),f=e(f);var l="undefined"!=typeof f;l||(f=n)}var c=S(f);if(c){var s=At.call(f);if(!Vt[s])return f;var g=ee(f)}if(!c||!t)return c&&!l?g?p(f):ie({},f):f;var v=Gt[s];switch(s){case $t:case Pt:return l?f:new v(+f);case qt:case Ct:return l?f:new v(f);case Ht:return l?f:v(f.source,ct.exec(f))}a||(a=[]),o||(o=[]);for(var y=a.length;y--;)if(a[y]==n)return o[y];return l||(f=g?v(f.length):{},g&&(wt.call(n,"index")&&(f.index=n.index),wt.call(n,"input")&&(f.input=n.input))),a.push(n),o.push(f),(g?G:te)(l?f:n,function(n,u){f[u]=d(n,t,e,r,a,o)
}),f}function m(n,r,t){return d(n,!0,r,t)}function b(n){var r=[];return re(n,function(n,t){E(n)&&r.push(t)}),r.sort()}function _(n,r){return n?wt.call(n,r):!1}function x(n){for(var r=-1,t=ue(n),e=t.length,u={};++r<e;){var a=t[r];u[n[a]]=a}return u}function w(n){return n===!0||n===!1||At.call(n)==$t}function j(n){return n instanceof Date||At.call(n)==Pt}function A(n){return n?1===n.nodeType:!1}function k(n){var r=!0;if(!n)return r;var t=At.call(n),e=n.length;return t==Nt||t==Ct||t==Ft||t==Bt&&"number"==typeof e&&E(n.splice)?!e:(te(n,function(){return r=!1
}),r)}function O(n,t,e,u,a,o){var f=e===et;if(e&&!f){e="undefined"==typeof u?e:i(e,u,2);var l=e(n,t);if("undefined"!=typeof l)return!!l}if(n===t)return 0!==n||1/n==1/t;var c=typeof n,s=typeof t;if(n===n&&(!n||"function"!=c&&"object"!=c)&&(!t||"function"!=s&&"object"!=s))return!1;if(null==n||null==t)return n===t;var p=At.call(n),g=At.call(t);if(p==Ft&&(p=Bt),g==Ft&&(g=Bt),p!=g)return!1;switch(p){case $t:case Pt:return+n==+t;case qt:return n!=+n?t!=+t:0==n?1/n==1/t:n==+t;case Ht:case Ct:return n==t+""
}var v=p==Nt;if(!v){if(n.__wrapped__||t.__wrapped__)return O(n.__wrapped__||n,t.__wrapped__||t,e,u,a,o);if(p!=Bt)return!1;var y=n.constructor,h=t.constructor;if(y!=h&&!(E(y)&&y instanceof y&&E(h)&&h instanceof h))return!1}a||(a=[]),o||(o=[]);for(var d=a.length;d--;)if(a[d]==n)return o[d]==t;var m=0;if(l=!0,a.push(n),o.push(t),v){if(d=n.length,m=t.length,l=m==n.length,!l&&!f)return l;for(;m--;){var b=d,_=t[m];if(f)for(;b--&&!(l=O(n[b],_,e,u,a,o)););else if(!(l=O(n[m],_,e,u,a,o)))break}return l}return re(t,function(t,i,f){return wt.call(f,i)?(m++,l=wt.call(n,i)&&O(n[i],t,e,u,a,o)):r
}),l&&!f&&re(n,function(n,t,e){return wt.call(e,t)?l=--m>-1:r}),l}function I(n){return It(n)&&!Et(parseFloat(n))}function E(n){return"function"==typeof n}function S(n){return n?Jt[typeof n]:!1}function L(n){return T(n)&&n!=+n}function R(n){return null===n}function T(n){return"number"==typeof n||At.call(n)==qt}function F(n){return n instanceof RegExp||At.call(n)==Ht}function N(n){return"string"==typeof n||At.call(n)==Ct}function $(n){return"undefined"==typeof n}function P(n,r,t){var e=arguments,u=0,a=2;
if(!S(n))return n;if(t===et)var o=e[3],f=e[4],l=e[5];else f=[],l=[],"number"!=typeof t&&(a=e.length),a>3&&"function"==typeof e[a-2]?o=i(e[--a-1],e[a--],2):a>2&&"function"==typeof e[a-1]&&(o=e[--a]);for(;++u<a;)(ee(e[u])?G:te)(e[u],function(r,t){var e,u,a=r,i=n[t];if(r&&((u=ee(r))||le(r))){for(var c=f.length;c--;)if(e=f[c]==r){i=l[c];break}e||(i=u?ee(i)?i:[]:le(i)?i:{},o&&(a=o(i,r),"undefined"!=typeof a&&(i=a)),f.push(r),l.push(i),o||(i=P(i,r,et,o,f,l)))}else o&&(a=o(i,r),"undefined"==typeof a&&(a=r)),"undefined"!=typeof a&&(i=a);
n[t]=i});return n}function D(n,r,t){var e="function"==typeof r,u={};if(e)r=i(r,t);else var a=bt.apply(nt,arguments);return re(n,function(n,t,o){(e?!r(n,t,o):sr(a,t,1)<0)&&(u[t]=n)}),u}function q(n){for(var r=-1,t=ue(n),e=t.length,u=Array(e);++r<e;){var a=t[r];u[r]=[a,n[a]]}return u}function B(n,r,t){var e={};if("function"!=typeof r)for(var u=0,a=bt.apply(nt,arguments),o=S(n)?a.length:0;++u<o;){var f=a[u];f in n&&(e[f]=n[f])}else r=i(r,t),re(n,function(n,t,u){r(n,t,u)&&(e[t]=n)});return e}function H(n){for(var r=-1,t=ue(n),e=t.length,u=Array(e);++r<e;)u[r]=n[t[r]];
return u}function C(n){for(var r=-1,t=bt.apply(nt,p(arguments,1)),e=t.length,u=Array(e);++r<e;)u[r]=n[t[r]];return u}function K(n,t,e){var u=-1,a=n?n.length:0,o=!1;return e=(e<0?Lt(0,a+e):e)||0,"number"==typeof a?o=(N(n)?n.indexOf(t,e):sr(n,t,e))>-1:ne(n,function(n){return++u<e?r:!(o=n===t)}),o}function M(n,r,t){var e={};return r=i(r,t),G(n,function(n,t,u){t=r(n,t,u)+"",wt.call(e,t)?e[t]++:e[t]=1}),e}function z(n,r,t){var e=!0;if(r=i(r,t),ee(n))for(var u=-1,a=n.length;++u<a&&(e=!!r(n[u],u,n)););else ne(n,function(n,t,u){return e=!!r(n,t,u)
});return e}function U(n,r,t){var e=[];if(r=i(r,t),ee(n))for(var u=-1,a=n.length;++u<a;){var o=n[u];r(o,u,n)&&e.push(o)}else ne(n,function(n,t,u){r(n,t,u)&&e.push(n)});return e}function V(n,t,e){var u;return t=i(t,e),G(n,function(n,e,a){return t(n,e,a)?(u=n,!1):r}),u}function G(n,r,t){if(r&&"undefined"==typeof t&&ee(n))for(var e=-1,u=n.length;++e<u&&r(n[e],e,n)!==!1;);else ne(n,r,t);return n}function J(n,r,t){var e={};return r=i(r,t),G(n,function(n,t,u){t=r(n,t,u)+"",(wt.call(e,t)?e[t]:e[t]=[]).push(n)
}),e}function Q(n,r){var t=p(arguments,2),e=-1,u="function"==typeof r,a=n?n.length:0,o=Array("number"==typeof a?a:0);return G(n,function(n){o[++e]=(u?r:n[r]).apply(n,t)}),o}function W(n,r,t){var e=-1,u=n?n.length:0,a=Array("number"==typeof u?u:0);if(r=i(r,t),ee(n))for(;++e<u;)a[e]=r(n[e],e,n);else ne(n,function(n,t,u){a[++e]=r(n,t,u)});return a}function X(n,r,t){var e=-1/0,a=e;if(!r&&ee(n))for(var o=-1,f=n.length;++o<f;){var l=n[o];l>a&&(a=l)}else r=!r&&N(n)?u:i(r,t),ne(n,function(n,t,u){var o=r(n,t,u);
o>e&&(e=o,a=n)});return a}function Y(n,r,t){var e=1/0,a=e;if(!r&&ee(n))for(var o=-1,f=n.length;++o<f;){var l=n[o];l<a&&(a=l)}else r=!r&&N(n)?u:i(r,t),ne(n,function(n,t,u){var o=r(n,t,u);o<e&&(e=o,a=n)});return a}function Z(n,r,t,e){var u=arguments.length<3;if(r=i(r,e,4),ee(n)){var a=-1,o=n.length;for(u&&(t=n[++a]);++a<o;)t=r(t,n[a],a,n)}else ne(n,function(n,e,a){t=u?(u=!1,n):r(t,n,e,a)});return t}function nr(n,r,t,e){var u=n,a=n?n.length:0,o=arguments.length<3;if("number"!=typeof a){var f=ue(n);a=f.length
}return r=i(r,e,4),G(n,function(n,e,i){e=f?f[--a]:--a,t=o?(o=!1,u[e]):r(t,u[e],e,i)}),t}function rr(n,r,t){return r=i(r,t),U(n,function(n,t,e){return!r(n,t,e)})}function tr(n){var r=-1,t=n?n.length:0,e=Array("number"==typeof t?t:0);return G(n,function(n){var t=_t(Tt()*(++r+1));e[r]=e[t],e[t]=n}),e}function er(n){var r=n?n.length:0;return"number"==typeof r?r:ue(n).length}function ur(n,r,t){var e;if(r=i(r,t),ee(n))for(var u=-1,a=n.length;++u<a&&!(e=r(n[u],u,n)););else ne(n,function(n,t,u){return!(e=r(n,t,u))
});return!!e}function ar(n,r,t){var e=-1,u=n?n.length:0,o=Array("number"==typeof u?u:0);for(r=i(r,t),G(n,function(n,t,u){o[++e]={criteria:r(n,t,u),index:e,value:n}}),u=o.length,o.sort(a);u--;)o[u]=o[u].value;return o}function or(n){return n&&"number"==typeof n.length?p(n):H(n)}function ir(n){for(var r=-1,t=n?n.length:0,e=[];++r<t;){var u=n[r];u&&e.push(u)}return e}function fr(n){for(var r=-1,t=n?n.length:0,u=bt.apply(nt,arguments),a=e(u,t),o=[];++r<t;){var i=n[r];a(i)||o.push(i)}return o}function lr(n,r,t){if(n){var e=0,u=n.length;
if("number"!=typeof r&&null!=r){var a=-1;for(r=i(r,t);++a<u&&r(n[a],a,n);)e++}else if(e=r,null==e||t)return n[0];return p(n,0,Rt(Lt(0,e),u))}}function cr(n,r){for(var t=-1,e=n?n.length:0,u=[];++t<e;){var a=n[t];ee(a)?jt.apply(u,r?a:cr(a)):u.push(a)}return u}function sr(n,r,t){var e=-1,u=n?n.length:0;if("number"==typeof t)e=(t<0?Lt(0,u+t):t||0)-1;else if(t)return e=br(n,r),n[e]===r?e:-1;for(;++e<u;)if(n[e]===r)return e;return-1}function pr(n,r,t){if(!n)return[];var e=0,u=n.length;if("number"!=typeof r&&null!=r){var a=u;
for(r=i(r,t);a--&&r(n[a],a,n);)e++}else e=null==r||t?1:r||e;return p(n,0,Rt(Lt(0,u-e),u))}function gr(n){var r=arguments,t=r.length,u={0:{}},a=-1,o=n?n.length:0,i=o>=100,f=[],l=f;n:for(;++a<o;){var c=n[a];if(i)var s=c+"",p=wt.call(u[0],s)?!(l=u[0][s]):l=u[0][s]=[];if(p||sr(l,c)<0){i&&l.push(c);for(var g=t;--g;)if(!(u[g]||(u[g]=e(r[g],0,100)))(c))continue n;f.push(c)}}return f}function vr(n,r,t){if(n){var e=0,u=n.length;if("number"!=typeof r&&null!=r){var a=u;for(r=i(r,t);a--&&r(n[a],a,n);)e++}else if(e=r,null==e||t)return n[u-1];
return p(n,Lt(0,u-e))}}function yr(n,r,t){var e=n?n.length:0;for("number"==typeof t&&(e=(t<0?Lt(0,e+t):Rt(t,e-1))+1);e--;)if(n[e]===r)return e;return-1}function hr(n,r){for(var t=-1,e=n?n.length:0,u={};++t<e;){var a=n[t];r?u[a]=r[t]:u[a[0]]=a[1]}return u}function dr(n,r,t){n=+n||0,t=+t||1,null==r&&(r=n,n=0);for(var e=-1,u=Lt(0,mt((r-n)/t)),a=Array(u);++e<u;)a[e]=n,n+=t;return a}function mr(n,r,t){if("number"!=typeof r&&null!=r){var e=0,u=-1,a=n?n.length:0;for(r=i(r,t);++u<a&&r(n[u],u,n);)e++}else e=null==r||t?1:Lt(0,r);
return p(n,e)}function br(n,r,t,e){var u=0,a=n?n.length:u;for(t=t?i(t,e,1):Br,r=t(r);u<a;){var o=u+a>>>1;t(n[o])<r?u=o+1:a=o}return u}function _r(){return xr(bt.apply(nt,arguments))}function xr(n,r,t,e){var u=-1,a=n?n.length:0,o=[],f=o;"function"==typeof r&&(e=t,t=r,r=!1);var l=!r&&a>=75;if(l)var c={};for(t&&(f=[],t=i(t,e));++u<a;){var s=n[u],p=t?t(s,u,n):s;if(l)var g=p+"",v=wt.call(c,g)?!(f=c[g]):f=c[g]=[];(r?!u||f[f.length-1]!==p:v||sr(f,p)<0)&&((t||l)&&f.push(p),o.push(s))}return o}function wr(n){for(var r=-1,t=n?n.length:0,u=e(arguments,1),a=[];++r<t;){var o=n[r];
u(o)||a.push(o)}return a}function jr(n){for(var r=-1,t=n?X(ce(arguments,"length")):0,e=Array(t);++r<t;)e[r]=ce(arguments,r);return e}function Ar(n,t){return n<1?t():function(){return--n<1?t.apply(this,arguments):r}}function kr(n,r){return zt||kt&&arguments.length>2?kt.call.apply(kt,arguments):o(n,r,p(arguments,2))}function Or(n){for(var r=bt.apply(nt,arguments),t=r.length>1?0:(r=b(n),-1),e=r.length;++t<e;){var u=r[t];n[u]=kr(n[u],n)}return n}function Ir(n,r){return o(n,r,p(arguments,2))}function Er(){var n=arguments;
return function(){for(var r=arguments,t=n.length;t--;)r=[n[t].apply(this,r)];return r[0]}}function Sr(n,r,t){function e(){i=null,t||(a=n.apply(o,u))}var u,a,o,i;return function(){var f=t&&!i;return u=arguments,o=this,clearTimeout(i),i=setTimeout(e,r),f&&(a=n.apply(o,u)),a}}function Lr(n,t){var e=p(arguments,2);return setTimeout(function(){n.apply(r,e)},t)}function Rr(n){var t=p(arguments,1);return setTimeout(function(){n.apply(r,t)},1)}function Tr(n,r){var t={};return function(){var e=(r?r.apply(this,arguments):arguments[0])+"";
return wt.call(t,e)?t[e]:t[e]=n.apply(this,arguments)}}function Fr(n){var r,t;return function(){return r?t:(r=!0,t=n.apply(this,arguments),n=null,t)}}function Nr(n){return o(n,p(arguments,1))}function $r(n){return o(n,p(arguments,1),null,et)}function Pr(n,r){function t(){i=new Date,o=null,u=n.apply(a,e)}var e,u,a,o,i=0;return function(){var f=new Date,l=r-(f-i);return e=arguments,a=this,l>0?o||(o=setTimeout(t,l)):(clearTimeout(o),o=null,i=f,u=n.apply(a,e)),u}}function Dr(n,r){return function(){var t=[n];
return jt.apply(t,arguments),r.apply(this,t)}}function qr(n){return null==n?"":(n+"").replace(yt,c)}function Br(n){return n}function Hr(n){G(b(n),function(r){var e=t[r]=n[r];t.prototype[r]=function(){var n=[this.__wrapped__];return jt.apply(n,arguments),new t(e.apply(t,n))}})}function Cr(){return n._=at,this}function Kr(n,r){return null==n&&null==r&&(r=1),n=+n||0,null==r&&(r=n,n=0),n+_t(Tt()*((+r||0)-n+1))}function Mr(n,t){var e=n?n[t]:r;return E(e)?n[t]():e}function zr(n,e,u){var a=t.templateSettings;
n||(n=""),u=fe({},u,a);var o,i=fe({},u.imports,a.imports),f=ue(i),c=H(i),s=0,p=u.interpolate||vt,g="__p += '",v=RegExp((u.escape||vt).source+"|"+p.source+"|"+(p===gt?pt:vt).source+"|"+(u.evaluate||vt).source+"|$","g");n.replace(v,function(r,t,e,u,a,i){return e||(e=u),g+=n.slice(s,i).replace(ht,l),t&&(g+="' +\n__e("+t+") +\n'"),a&&(o=!0,g+="';\n"+a+";\n__p += '"),e&&(g+="' +\n((__t = ("+e+")) == null ? '' : __t) +\n'"),s=i+r.length,r}),g+="';\n";var y=u.variable,h=y;h||(y="obj",g="with ("+y+") {\n"+g+"\n}\n"),g=(o?g.replace(it,""):g).replace(ft,"$1").replace(lt,"$1;"),g="function("+y+") {\n"+(h?"":y+" || ("+y+" = {});\n")+"var __t, __p = '', __e = _.escape"+(o?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+g+"return __p\n}";
var d="\n/*\n//@ sourceURL="+(u.sourceURL||"/lodash/template/source["+dt++ +"]")+"\n*/";try{var m=Function(f,"return "+g+d).apply(r,c)}catch(b){throw b.source=g,b}return e?m(e):(m.source=g,m)}function Ur(n,r,t){n=+n||0;for(var e=-1,u=Array(n);++e<n;)u[e]=r.call(t,e);return u}function Vr(n){return null==n?"":(n+"").replace(ot,g)}function Gr(n){var r=++tt;return(null==n?"":n+"")+r}function Jr(n,r){return r(n),n}function Qr(){return this.__wrapped__+""}function Wr(){return this.__wrapped__}var Xr="object"==typeof exports&&exports,Yr="object"==typeof module&&module&&module.exports==Xr&&module,Zr="object"==typeof global&&global;
Zr.global===Zr&&(n=Zr);var nt=[],rt={},tt=0,et=rt,ut=30,at=n._,ot=/&(?:amp|lt|gt|quot|#39);/g,it=/\b__p \+= '';/g,ft=/\b(__p \+=) '' \+/g,lt=/(__e\(.*?\)|\b__t\)) \+\n'';/g,ct=/\w*$/,st=RegExp("^"+(rt.valueOf+"").replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/valueOf|for [^\]]+/g,".+?")+"$"),pt=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,gt=/<%=([\s\S]+?)%>/g,vt=/($^)/,yt=/[&<>"']/g,ht=/['\n\r\t\u2028\u2029\\]/g,dt=0,mt=Math.ceil,bt=nt.concat,_t=Math.floor,xt=st.test(xt=Object.getPrototypeOf)&&xt,wt=rt.hasOwnProperty,jt=nt.push,At=rt.toString,kt=st.test(kt=p.bind)&&kt,Ot=st.test(Ot=Array.isArray)&&Ot,It=n.isFinite,Et=n.isNaN,St=st.test(St=Object.keys)&&St,Lt=Math.max,Rt=Math.min,Tt=Math.random,Ft="[object Arguments]",Nt="[object Array]",$t="[object Boolean]",Pt="[object Date]",Dt="[object Function]",qt="[object Number]",Bt="[object Object]",Ht="[object RegExp]",Ct="[object String]",Kt=!!n.attachEvent,Mt=kt&&!/\n|true/.test(kt+Kt),zt=kt&&!Mt,Ut=St&&(Kt||Mt),Vt={};
Vt[Dt]=!1,Vt[Ft]=Vt[Nt]=Vt[$t]=Vt[Pt]=Vt[qt]=Vt[Bt]=Vt[Ht]=Vt[Ct]=!0;var Gt={};Gt[Nt]=Array,Gt[$t]=Boolean,Gt[Pt]=Date,Gt[Bt]=Object,Gt[qt]=Number,Gt[Ht]=RegExp,Gt[Ct]=String;var Jt={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},Qt={"\\":"\\","'":"'","\n":"n","\r":"r"," ":"t","\u2028":"u2028","\u2029":"u2029"};t.templateSettings={escape:/<%-([\s\S]+?)%>/g,evaluate:/<%([\s\S]+?)%>/g,interpolate:gt,variable:"",imports:{_:t}};var Wt=function(n){var r="var index, iterable = "+n.firstArg+", result = iterable;\nif (!iterable) return result;\n"+n.top+";\n";
return n.arrays&&(r+="var length = iterable.length; index = -1;\nif ("+n.arrays+") {\n while (++index < length) {\n "+n.loop+"\n }\n}\nelse { "),n.isKeysFast&&n.useHas?r+="\n var ownIndex = -1,\n ownProps = objectTypes[typeof iterable] ? nativeKeys(iterable) : [],\n length = ownProps.length;\n\n while (++ownIndex < length) {\n index = ownProps[ownIndex];\n "+n.loop+"\n } ":(r+="\n for (index in iterable) {",n.useHas&&(r+="\n if (",n.useHas&&(r+="hasOwnProperty.call(iterable, index)"),r+=") { "),r+=n.loop+"; ",n.useHas&&(r+="\n }"),r+="\n } "),n.arrays&&(r+="\n}"),r+=n.bottom+";\nreturn result"
},Xt={args:"object, source, guard",top:"var args = arguments,\n argsIndex = 0,\n argsLength = typeof guard == 'number' ? 2 : args.length;\nwhile (++argsIndex < argsLength) {\n iterable = args[argsIndex];\n if (iterable && objectTypes[typeof iterable]) {",loop:"if (typeof result[index] == 'undefined') result[index] = iterable[index]",bottom:" }\n}"},Yt={args:"collection, callback, thisArg",top:"callback = callback && typeof thisArg == 'undefined' ? callback : createCallback(callback, thisArg)",arrays:"typeof length == 'number'",loop:"if (callback(iterable[index], index, collection) === false) return result"},Zt={top:"if (!objectTypes[typeof iterable]) return result;\n"+Yt.top,arrays:!1},ne=f(Yt),re=f(Yt,Zt,{useHas:!1}),te=f(Yt,Zt),ee=Ot||function(n){return n instanceof Array||At.call(n)==Nt
},ue=St?function(n){return S(n)?St(n):[]}:h,ae={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},oe=x(ae),ie=f(Xt,{top:Xt.top.replace(";",";\nif (argsLength > 3 && typeof args[argsLength - 2] == 'function') {\n var callback = createCallback(args[--argsLength - 1], args[argsLength--], 2);\n} else if (argsLength > 2 && typeof args[argsLength - 1] == 'function') {\n callback = args[--argsLength];\n}"),loop:"result[index] = callback ? callback(result[index], iterable[index]) : iterable[index]"}),fe=f(Xt);
E(/x/)&&(E=function(n){return n instanceof Function||At.call(n)==Dt});var le=xt?function(n){if(!n||"object"!=typeof n)return!1;var r=n.valueOf,t="function"==typeof r&&(t=xt(r))&&xt(t);return t?n==t||xt(n)==t&&!v(n):y(n)}:y,ce=W,se=U;Mt&&Yr&&"function"==typeof setImmediate&&(Rr=kr(setImmediate,n)),t.after=Ar,t.assign=ie,t.at=C,t.bind=kr,t.bindAll=Or,t.bindKey=Ir,t.compact=ir,t.compose=Er,t.countBy=M,t.debounce=Sr,t.defaults=fe,t.defer=Rr,t.delay=Lr,t.difference=fr,t.filter=U,t.flatten=cr,t.forEach=G,t.forIn=re,t.forOwn=te,t.functions=b,t.groupBy=J,t.initial=pr,t.intersection=gr,t.invert=x,t.invoke=Q,t.keys=ue,t.map=W,t.max=X,t.memoize=Tr,t.merge=P,t.min=Y,t.object=hr,t.omit=D,t.once=Fr,t.pairs=q,t.partial=Nr,t.partialRight=$r,t.pick=B,t.pluck=ce,t.range=dr,t.reject=rr,t.rest=mr,t.shuffle=tr,t.sortBy=ar,t.tap=Jr,t.throttle=Pr,t.times=Ur,t.toArray=or,t.union=_r,t.uniq=xr,t.values=H,t.where=se,t.without=wr,t.wrap=Dr,t.zip=jr,t.collect=W,t.drop=mr,t.each=G,t.extend=ie,t.methods=b,t.select=U,t.tail=mr,t.unique=xr,Hr(t),t.clone=d,t.cloneDeep=m,t.contains=K,t.escape=qr,t.every=z,t.find=V,t.has=_,t.identity=Br,t.indexOf=sr,t.isArguments=v,t.isArray=ee,t.isBoolean=w,t.isDate=j,t.isElement=A,t.isEmpty=k,t.isEqual=O,t.isFinite=I,t.isFunction=E,t.isNaN=L,t.isNull=R,t.isNumber=T,t.isObject=S,t.isPlainObject=le,t.isRegExp=F,t.isString=N,t.isUndefined=$,t.lastIndexOf=yr,t.mixin=Hr,t.noConflict=Cr,t.random=Kr,t.reduce=Z,t.reduceRight=nr,t.result=Mr,t.size=er,t.some=ur,t.sortedIndex=br,t.template=zr,t.unescape=Vr,t.uniqueId=Gr,t.all=z,t.any=ur,t.detect=V,t.foldl=Z,t.foldr=nr,t.include=K,t.inject=Z,te(t,function(n,r){t.prototype[r]||(t.prototype[r]=function(){var r=[this.__wrapped__];
return jt.apply(r,arguments),n.apply(t,r)})}),t.first=lr,t.last=vr,t.take=lr,t.head=lr,te(t,function(n,r){t.prototype[r]||(t.prototype[r]=function(r,e){var u=n(this.__wrapped__,r,e);return null==r||e&&"function"!=typeof r?u:new t(u)})}),t.VERSION="1.0.2",t.prototype.toString=Qr,t.prototype.value=Wr,t.prototype.valueOf=Wr,ne(["join","pop","shift"],function(n){var r=nt[n];t.prototype[n]=function(){return r.apply(this.__wrapped__,arguments)}}),ne(["push","reverse","sort","unshift"],function(n){var r=nt[n];
t.prototype[n]=function(){return r.apply(this.__wrapped__,arguments),this}}),ne(["concat","slice","splice"],function(n){var r=nt[n];t.prototype[n]=function(){return new t(r.apply(this.__wrapped__,arguments))}}),"function"==typeof define&&"object"==typeof define.amd&&define.amd?(n._=t,define(function(){return t})):Xr?Yr?(Yr.exports=t)._=t:Xr._=t:n._=t})(this);

4307
dist/lodash.underscore.js vendored Normal file

File diff suppressed because it is too large Load Diff

34
dist/lodash.underscore.min.js vendored Normal file
View File

@@ -0,0 +1,34 @@
/**
* @license
* Lo-Dash 1.0.2 (Custom Build) lodash.com/license
* Build: `lodash underscore -o ./dist/lodash.underscore.js`
* Underscore.js 1.4.4 underscorejs.org/LICENSE
*/
;(function(n,t){function r(n,t){var r;if(n&&qt[typeof n])for(r in t||(t=G),n)if(t(n[r],r,n)===tt)break}function e(n,t,r){if(n){t=t&&typeof r=="undefined"?t:a(t,r);var e=n.length;if(r=-1,typeof e=="number")for(;++r<e&&t(n[r],r,n)!==tt;);else for(r in n)if(pt.call(n,r)&&t(n[r],r,n)===tt)break}}function u(n){return n&&typeof n=="object"&&n.__wrapped__?n:this instanceof u?(this.__wrapped__=n,void 0):new u(n)}function o(n,t){var r=n.b,e=t.b;if(n=n.a,t=t.a,n!==t){if(n>t||typeof n=="undefined")return 1;if(n<t||typeof t=="undefined")return-1
}return r<e?-1:1}function i(n,t,r){function e(){var a=arguments,f=o?this:t;return u||(n=t[i]),r.length&&(a=a.length?(a=p(a),r.concat(a)):r),this instanceof e?(l.prototype=n.prototype,f=new l,l.prototype=K,a=n.apply(f,a),w(a)?a:f):n.apply(f,a)}var u=j(n),o=!r,i=t;return o&&(r=t),u||(t=n),e}function a(n,t,r){if(n==K)return G;var e=typeof n;if("function"!=e){if("object"!=e)return function(t){return t[n]};var u=Dt(n);return function(t){for(var r=u.length,e=L;r--&&(e=t[u[r]]===n[u[r]]););return e}}return typeof t!="undefined"?1===r?function(r){return n.call(t,r)
}:2===r?function(r,e){return n.call(t,r,e)}:4===r?function(r,e,u,o){return n.call(t,r,e,u,o)}:function(r,e,u){return n.call(t,r,e,u)}:n}function f(n){return"\\"+It[n]}function c(n){return Mt[n]}function l(){}function p(n,t,r){t||(t=0),typeof r=="undefined"&&(r=n?n.length:0);var e=-1;r=r-t||0;for(var u=Array(0>r?0:r);++e<r;)u[e]=n[t+e];return u}function s(n){return $t[n]}function v(n){return vt.call(n)==wt}function h(n){var t,r=[],e=function(n,t){r.push(t)};if(n&&qt[typeof n])for(t in e||(e=G),n)if(pt.call(n,t)&&e(n[t],t,n)===tt)break;
return r}function g(n){if(!n)return n;for(var t=1,r=arguments.length;t<r;t++){var e=arguments[t];if(e)for(var u in e)n[u]=e[u]}return n}function y(n){if(!n)return n;for(var t=1,r=arguments.length;t<r;t++){var e=arguments[t];if(e)for(var u in e)n[u]==K&&(n[u]=e[u])}return n}function m(n){var t=[];return r(n,function(n,r){j(n)&&t.push(r)}),t.sort()}function _(n){for(var t=-1,r=Dt(n),e=r.length,u={};++t<e;){var o=r[t];u[n[o]]=o}return u}function d(n){if(!n)return J;if(Bt(n)||x(n))return!n.length;for(var t in n)if(pt.call(n,t))return L;
return J}function b(n,t,e,u){if(n===t)return 0!==n||1/n==1/t;var o=typeof n,i=typeof t;if(n===n&&(!n||"function"!=o&&"object"!=o)&&(!t||"function"!=i&&"object"!=i))return L;if(n==K||t==K)return n===t;if(i=vt.call(n),o=vt.call(t),i!=o)return L;switch(i){case xt:case Et:return+n==+t;case Ot:return n!=+n?t!=+t:0==n?1/n==1/t:n==+t;case Nt:case kt:return n==t+""}if(o=i==At,!o){if(n.__wrapped__||t.__wrapped__)return b(n.__wrapped__||n,t.__wrapped__||t,e,u);if(i!=St)return L;var i=n.constructor,a=t.constructor;
if(i!=a&&(!j(i)||!(i instanceof i&&j(a)&&a instanceof a)))return L}for(e||(e=[]),u||(u=[]),i=e.length;i--;)if(e[i]==n)return u[i]==t;var f=J,c=0;if(e.push(n),u.push(t),o){if(c=t.length,f=c==n.length)for(;c--&&(f=b(n[c],t[c],e,u)););return f}return r(t,function(t,r,o){return pt.call(o,r)?(c++,!(f=pt.call(n,r)&&b(n[r],t,e,u))&&tt):void 0}),f&&r(n,function(n,t,r){return pt.call(r,t)?!(f=-1<--c)&&tt:void 0}),f}function j(n){return typeof n=="function"}function w(n){return n?qt[typeof n]:L}function A(n){return typeof n=="number"||vt.call(n)==Ot
}function x(n){return typeof n=="string"||vt.call(n)==kt}function E(n){for(var t=-1,r=Dt(n),e=r.length,u=Array(e);++t<e;)u[t]=n[r[t]];return u}function O(n,t){var r=L;return typeof(n?n.length:0)=="number"?r=-1<z(n,t):e(n,function(n){return(r=n===t)&&tt}),r}function S(n,t,r){var u=J;if(t=a(t,r),Bt(n)){r=-1;for(var o=n.length;++r<o&&(u=!!t(n[r],r,n)););}else e(n,function(n,r,e){return!(u=!!t(n,r,e))&&tt});return u}function N(n,t,r){var u=[];if(t=a(t,r),Bt(n)){r=-1;for(var o=n.length;++r<o;){var i=n[r];
t(i,r,n)&&u.push(i)}}else e(n,function(n,r,e){t(n,r,e)&&u.push(n)});return u}function k(n,t,r){var e;return t=a(t,r),F(n,function(n,r,u){return t(n,r,u)?(e=n,tt):void 0}),e}function F(n,t,r){if(t&&typeof r=="undefined"&&Bt(n)){r=-1;for(var u=n.length;++r<u&&t(n[r],r,n)!==tt;);}else e(n,t,r)}function R(n,t,r){var u=-1,o=n?n.length:0,i=Array(typeof o=="number"?o:0);if(t=a(t,r),Bt(n))for(;++u<o;)i[u]=t(n[u],u,n);else e(n,function(n,r,e){i[++u]=t(n,r,e)});return i}function T(n,t,r){var u=-1/0,o=u;if(!t&&Bt(n)){r=-1;
for(var i=n.length;++r<i;){var f=n[r];f>o&&(o=f)}}else t=a(t,r),e(n,function(n,r,e){r=t(n,r,e),r>u&&(u=r,o=n)});return o}function q(n,t,r,u){var o=3>arguments.length;if(t=a(t,u,4),Bt(n)){var i=-1,f=n.length;for(o&&(r=n[++i]);++i<f;)r=t(r,n[i],i,n)}else e(n,function(n,e,u){r=o?(o=L,n):t(r,n,e,u)});return r}function I(n,t,r,e){var u=n?n.length:0,o=3>arguments.length;if(typeof u!="number")var i=Dt(n),u=i.length;return t=a(t,e,4),F(n,function(e,a,f){a=i?i[--u]:--u,r=o?(o=L,n[a]):t(r,n[a],a,f)}),r}function B(n,t,r){var u;
if(t=a(t,r),Bt(n)){r=-1;for(var o=n.length;++r<o&&!(u=t(n[r],r,n)););}else e(n,function(n,r,e){return(u=t(n,r,e))&&tt});return!!u}function D(n,t,r){return r&&d(t)?K:(r?k:N)(n,t)}function M(n,t,r){if(n){var e=0,u=n.length;if(typeof t!="number"&&t!=K){var o=-1;for(t=a(t,r);++o<u&&t(n[o],o,n);)e++}else if(e=t,e==K||r)return n[0];return p(n,0,bt(dt(0,e),u))}}function $(n,t){for(var r=-1,e=n?n.length:0,u=[];++r<e;){var o=n[r];Bt(o)?st.apply(u,t?o:$(o)):u.push(o)}return u}function z(n,t,r){var e=-1,u=n?n.length:0;
if(typeof r=="number")e=(0>r?dt(0,u+r):r||0)-1;else if(r)return e=P(n,t),n[e]===t?e:-1;for(;++e<u;)if(n[e]===t)return e;return-1}function C(n,t,r){if(typeof t!="number"&&t!=K){var e=0,u=-1,o=n?n.length:0;for(t=a(t,r);++u<o&&t(n[u],u,n);)e++}else e=t==K||r?1:dt(0,t);return p(n,e)}function P(n,t,r,e){var u=0,o=n?n.length:u;for(r=r?a(r,e,1):G,t=r(t);u<o;)e=u+o>>>1,r(n[e])<t?u=e+1:o=e;return u}function U(n,t,r,e){var u=-1,o=n?n.length:0,i=[],f=i;for(typeof t=="function"&&(e=r,r=t,t=L),r&&(f=[],r=a(r,e));++u<o;){e=n[u];
var c=r?r(e,u,n):e;(t?!u||f[f.length-1]!==c:0>z(f,c))&&(r&&f.push(c),i.push(e))}return i}function V(n,t){return Ft||ht&&2<arguments.length?ht.call.apply(ht,arguments):i(n,t,p(arguments,2))}function W(n){var r=p(arguments,1);return setTimeout(function(){n.apply(t,r)},1)}function G(n){return n}function H(n){F(m(n),function(t){var r=u[t]=n[t];u.prototype[t]=function(){var n=[this.__wrapped__];return st.apply(n,arguments),n=r.apply(u,n),this.__chain__&&(n=new u(n),n.__chain__=J),n}})}var J=!0,K=null,L=!1,Q=typeof exports=="object"&&exports,X=typeof module=="object"&&module&&module.exports==Q&&module,Y=typeof global=="object"&&global;
Y.global===Y&&(n=Y);var Z=[],Y={},nt=0,tt=Y,rt=n._,et=/&(?:amp|lt|gt|quot|#39);/g,ut=RegExp("^"+(Y.valueOf+"").replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/valueOf|for [^\]]+/g,".+?")+"$"),ot=/($^)/,it=/[&<>"']/g,at=/['\n\r\t\u2028\u2029\\]/g,ft=Math.ceil,ct=Z.concat,lt=Math.floor,pt=Y.hasOwnProperty,st=Z.push,vt=Y.toString,ht=ut.test(ht=p.bind)&&ht,gt=ut.test(gt=Array.isArray)&&gt,yt=n.isFinite,mt=n.isNaN,_t=ut.test(_t=Object.keys)&&_t,dt=Math.max,bt=Math.min,jt=Math.random,wt="[object Arguments]",At="[object Array]",xt="[object Boolean]",Et="[object Date]",Ot="[object Number]",St="[object Object]",Nt="[object RegExp]",kt="[object String]",Y=!!n.attachEvent,Y=ht&&!/\n|true/.test(ht+Y),Ft=ht&&!Y,Rt=(Rt={0:1,length:1},Z.splice.call(Rt,0,1),Rt[0]),Tt=arguments.constructor==Object,qt={"boolean":L,"function":J,object:J,number:L,string:L,undefined:L},It={"\\":"\\","'":"'","\n":"n","\r":"r"," ":"t","\u2028":"u2028","\u2029":"u2029"};
u.templateSettings={escape:/<%-([\s\S]+?)%>/g,evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,variable:""},v(arguments)||(v=function(n){return n?pt.call(n,"callee"):L});var Bt=gt||function(n){return Tt&&n instanceof Array||vt.call(n)==At},Dt=_t?function(n){return w(n)?_t(n):[]}:h,Mt={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},$t=_(Mt);j(/x/)&&(j=function(n){return n instanceof Function||"[object Function]"==vt.call(n)});var zt=R;Y&&X&&typeof setImmediate=="function"&&(W=V(setImmediate,n)),u.after=function(n,t){return 1>n?t():function(){return 1>--n?t.apply(this,arguments):void 0
}},u.bind=V,u.bindAll=function(n){for(var t=ct.apply(Z,arguments),r=1<t.length?0:(t=m(n),-1),e=t.length;++r<e;){var u=t[r];n[u]=V(n[u],n)}return n},u.compact=function(n){for(var t=-1,r=n?n.length:0,e=[];++t<r;){var u=n[t];u&&e.push(u)}return e},u.compose=function(){var n=arguments;return function(){for(var t=arguments,r=n.length;r--;)t=[n[r].apply(this,t)];return t[0]}},u.countBy=function(n,t,r){var e={};return t=a(t,r),F(n,function(n,r,u){r=t(n,r,u)+"",pt.call(e,r)?e[r]++:e[r]=1}),e},u.debounce=function(n,t,r){function e(){a=K,r||(o=n.apply(i,u))
}var u,o,i,a;return function(){var f=r&&!a;return u=arguments,i=this,clearTimeout(a),a=setTimeout(e,t),f&&(o=n.apply(i,u)),o}},u.defaults=y,u.defer=W,u.delay=function(n,r){var e=p(arguments,2);return setTimeout(function(){n.apply(t,e)},r)},u.difference=function(n){for(var t=-1,r=n.length,e=ct.apply(Z,arguments),u=[];++t<r;){var o=n[t];0>z(e,o,r)&&u.push(o)}return u},u.filter=N,u.flatten=$,u.forEach=F,u.functions=m,u.groupBy=function(n,t,r){var e={};return t=a(t,r),F(n,function(n,r,u){r=t(n,r,u)+"",(pt.call(e,r)?e[r]:e[r]=[]).push(n)
}),e},u.initial=function(n,t,r){if(!n)return[];var e=0,u=n.length;if(typeof t!="number"&&t!=K){var o=u;for(t=a(t,r);o--&&t(n[o],o,n);)e++}else e=t==K||r?1:t||e;return p(n,0,bt(dt(0,u-e),u))},u.intersection=function(n){var t=arguments,r=t.length,e=-1,u=n?n.length:0,o=[];n:for(;++e<u;){var i=n[e];if(0>z(o,i)){for(var a=r;--a;)if(0>z(t[a],i))continue n;o.push(i)}}return o},u.invert=_,u.invoke=function(n,t){var r=p(arguments,2),e=-1,u=typeof t=="function",o=n?n.length:0,i=Array(typeof o=="number"?o:0);
return F(n,function(n){i[++e]=(u?t:n[t]).apply(n,r)}),i},u.keys=Dt,u.map=R,u.max=T,u.memoize=function(n,t){var r={};return function(){var e=(t?t.apply(this,arguments):arguments[0])+"";return pt.call(r,e)?r[e]:r[e]=n.apply(this,arguments)}},u.min=function(n,t,r){var u=1/0,o=u;if(!t&&Bt(n)){r=-1;for(var i=n.length;++r<i;){var f=n[r];f<o&&(o=f)}}else t=a(t,r),e(n,function(n,r,e){r=t(n,r,e),r<u&&(u=r,o=n)});return o},u.object=function(n,t){for(var r=-1,e=n?n.length:0,u={};++r<e;){var o=n[r];t?u[o]=t[r]:u[o[0]]=o[1]
}return u},u.omit=function(n){var t=ct.apply(Z,arguments),e={};return r(n,function(n,r){0>z(t,r,1)&&(e[r]=n)}),e},u.once=function(n){var t,r;return function(){return t?r:(t=J,r=n.apply(this,arguments),n=K,r)}},u.pairs=function(n){for(var t=-1,r=Dt(n),e=r.length,u=Array(e);++t<e;){var o=r[t];u[t]=[o,n[o]]}return u},u.partial=function(n){return i(n,p(arguments,1))},u.pick=function(n){for(var t=0,r=ct.apply(Z,arguments),e=r.length,u={};++t<e;){var o=r[t];o in n&&(u[o]=n[o])}return u},u.pluck=zt,u.range=function(n,t,r){n=+n||0,r=+r||1,t==K&&(t=n,n=0);
var e=-1;t=dt(0,ft((t-n)/r));for(var u=Array(t);++e<t;)u[e]=n,n+=r;return u},u.reject=function(n,t,r){return t=a(t,r),N(n,function(n,r,e){return!t(n,r,e)})},u.rest=C,u.shuffle=function(n){var t=-1,r=n?n.length:0,e=Array(typeof r=="number"?r:0);return F(n,function(n){var r=lt(jt()*(++t+1));e[t]=e[r],e[r]=n}),e},u.sortBy=function(n,t,r){var e=-1,u=n?n.length:0,i=Array(typeof u=="number"?u:0);for(t=a(t,r),F(n,function(n,r,u){i[++e]={a:t(n,r,u),b:e,c:n}}),u=i.length,i.sort(o);u--;)i[u]=i[u].c;return i
},u.tap=function(n,t){return t(n),n},u.throttle=function(n,t){function r(){a=new Date,i=K,u=n.apply(o,e)}var e,u,o,i,a=0;return function(){var f=new Date,c=t-(f-a);return e=arguments,o=this,0<c?i||(i=setTimeout(r,c)):(clearTimeout(i),i=K,a=f,u=n.apply(o,e)),u}},u.times=function(n,t,r){n=+n||0;for(var e=-1,u=Array(n);++e<n;)u[e]=t.call(r,e);return u},u.toArray=function(n){return n&&typeof n.length=="number"?p(n):E(n)},u.union=function(){return U(ct.apply(Z,arguments))},u.uniq=U,u.values=E,u.where=D,u.without=function(n){for(var t=-1,r=n.length,e=[];++t<r;){var u=n[t];
0>z(arguments,u,1)&&e.push(u)}return e},u.wrap=function(n,t){return function(){var r=[n];return st.apply(r,arguments),t.apply(this,r)}},u.zip=function(n){for(var t=-1,r=n?T(zt(arguments,"length")):0,e=Array(r);++t<r;)e[t]=zt(arguments,t);return e},u.collect=R,u.drop=C,u.each=F,u.extend=g,u.methods=m,u.select=N,u.tail=C,u.unique=U,u.clone=function(n){return w(n)?Bt(n)?p(n):g({},n):n},u.contains=O,u.escape=function(n){return n==K?"":(n+"").replace(it,c)},u.every=S,u.find=k,u.findWhere=function(n,t){return D(n,t,J)
},u.has=function(n,t){return n?pt.call(n,t):L},u.identity=G,u.indexOf=z,u.isArguments=v,u.isArray=Bt,u.isBoolean=function(n){return n===J||n===L||vt.call(n)==xt},u.isDate=function(n){return n instanceof Date||vt.call(n)==Et},u.isElement=function(n){return n?1===n.nodeType:L},u.isEmpty=d,u.isEqual=b,u.isFinite=function(n){return yt(n)&&!mt(parseFloat(n))},u.isFunction=j,u.isNaN=function(n){return A(n)&&n!=+n},u.isNull=function(n){return n===K},u.isNumber=A,u.isObject=w,u.isRegExp=function(n){return n instanceof RegExp||vt.call(n)==Nt
},u.isString=x,u.isUndefined=function(n){return typeof n=="undefined"},u.lastIndexOf=function(n,t,r){var e=n?n.length:0;for(typeof r=="number"&&(e=(0>r?dt(0,e+r):bt(r,e-1))+1);e--;)if(n[e]===t)return e;return-1},u.mixin=H,u.noConflict=function(){return n._=rt,this},u.random=function(n,t){return n==K&&t==K&&(t=1),n=+n||0,t==K&&(t=n,n=0),n+lt(jt()*((+t||0)-n+1))},u.reduce=q,u.reduceRight=I,u.result=function(n,t){var r=n?n[t]:K;return j(r)?n[t]():r},u.size=function(n){var t=n?n.length:0;return typeof t=="number"?t:Dt(n).length
},u.some=B,u.sortedIndex=P,u.template=function(n,t,r){n||(n=""),r=y({},r,u.templateSettings);var e=0,o="__p+='",i=r.variable;n.replace(RegExp((r.escape||ot).source+"|"+(r.interpolate||ot).source+"|"+(r.evaluate||ot).source+"|$","g"),function(t,r,u,i,a){return o+=n.slice(e,a).replace(at,f),r&&(o+="'+_['escape']("+r+")+'"),i&&(o+="';"+i+";__p+='"),u&&(o+="'+((__t=("+u+"))==null?'':__t)+'"),e=a+t.length,t}),o+="';\n",i||(i="obj",o="with("+i+"||{}){"+o+"}"),o="function("+i+"){var __t,__p='',__j=Array.prototype.join;function print(){__p+=__j.call(arguments,'')}"+o+"return __p}";
try{var a=Function("_","return "+o)(u)}catch(c){throw c.source=o,c}return t?a(t):(a.source=o,a)},u.unescape=function(n){return n==K?"":(n+"").replace(et,s)},u.uniqueId=function(n){var t=++nt+"";return n?n+t:t},u.all=S,u.any=B,u.detect=k,u.foldl=q,u.foldr=I,u.include=O,u.inject=q,u.first=M,u.last=function(n,t,r){if(n){var e=0,u=n.length;if(typeof t!="number"&&t!=K){var o=u;for(t=a(t,r);o--&&t(n[o],o,n);)e++}else if(e=t,e==K||r)return n[u-1];return p(n,dt(0,u-e))}},u.take=M,u.head=M,u.chain=function(n){return n=new u(n),n.__chain__=J,n
},u.VERSION="1.0.2",H(u),u.prototype.chain=function(){return this.__chain__=J,this},u.prototype.value=function(){return this.__wrapped__},e("pop push reverse shift sort splice unshift".split(" "),function(n){var t=Z[n];u.prototype[n]=function(){var n=this.__wrapped__;return t.apply(n,arguments),Rt&&0===n.length&&delete n[0],this}}),e(["concat","join","slice"],function(n){var t=Z[n];u.prototype[n]=function(){var n=t.apply(this.__wrapped__,arguments);return this.__chain__&&(n=new u(n),n.__chain__=J),n
}}),Q?X?(X.exports=u)._=u:Q._=u:n._=u})(this);

File diff suppressed because it is too large Load Diff

38
doc/parse.php Normal file
View File

@@ -0,0 +1,38 @@
<?php
// cleanup requested file path
$filePath = isset($_GET['f']) ? $_GET['f'] : 'lodash';
$filePath = preg_replace('#(\.*[\/])+#', '', $filePath);
$filePath .= preg_match('/\.[a-z]+$/', $filePath) ? '' : '.js';
// output filename
if (isset($_GET['o'])) {
$outputName = $_GET['o'];
} else if (isset($_SERVER['argv'][1])) {
$outputName = $_SERVER['argv'][1];
} else {
$outputName = basename($filePath);
}
/*--------------------------------------------------------------------------*/
require('../vendor/docdown/docdown.php');
// get package version
$version = json_decode(file_get_contents('../package.json'))->version;
// generate Markdown
$markdown = docdown(array(
'path' => '../' . $filePath,
'title' => '<a href="http://lodash.com/">Lo-Dash</a> <span>v' . $version . '</span>',
'toc' => 'categories',
'url' => 'https://github.com/lodash/lodash/blob/' . $version . '/lodash.js'
));
// save to a `.md` file
file_put_contents($outputName . '.md', $markdown);
// print
header('Content-Type: text/plain;charset=utf-8');
echo $markdown . PHP_EOL;
?>

1
index.js Executable file
View File

@@ -0,0 +1 @@
module.exports = require('./lodash');

17043
lodash.js

File diff suppressed because it is too large Load Diff

140
lodash.min.js vendored
View File

@@ -1,140 +0,0 @@
/**
* @license
* lodash 3.7.0 (Custom Build) lodash.com/license | Underscore.js 1.8.3 underscorejs.org/LICENSE
* Build: `lodash modern -o ./lodash.js`
*/
;(function(){function n(n,t){if(n!==t){var r=n===n,e=t===t;if(n>t||!r||n===w&&e)return 1;if(n<t||!e||t===w&&r)return-1}return 0}function t(n,t,r){for(var e=n.length,u=r?e:-1;r?u--:++u<e;)if(t(n[u],u,n))return u;return-1}function r(n,t,r){if(t!==t)return p(n,r);r-=1;for(var e=n.length;++r<e;)if(n[r]===t)return r;return-1}function e(n){return typeof n=="function"||false}function u(n){return typeof n=="string"?n:null==n?"":n+""}function o(n){return n.charCodeAt(0)}function i(n,t){for(var r=-1,e=n.length;++r<e&&-1<t.indexOf(n.charAt(r)););
return r}function f(n,t){for(var r=n.length;r--&&-1<t.indexOf(n.charAt(r)););return r}function a(t,r){return n(t.a,r.a)||t.b-r.b}function c(n){return $n[n]}function l(n){return Ln[n]}function s(n){return"\\"+Mn[n]}function p(n,t,r){var e=n.length;for(t+=r?0:-1;r?t--:++t<e;){var u=n[t];if(u!==u)return t}return-1}function h(n){return!!n&&typeof n=="object"}function _(n){return 160>=n&&9<=n&&13>=n||32==n||160==n||5760==n||6158==n||8192<=n&&(8202>=n||8232==n||8233==n||8239==n||8287==n||12288==n||65279==n);
}function v(n,t){for(var r=-1,e=n.length,u=-1,o=[];++r<e;)n[r]===t&&(n[r]=B,o[++u]=r);return o}function g(n){for(var t=-1,r=n.length;++t<r&&_(n.charCodeAt(t)););return t}function y(n){for(var t=n.length;t--&&_(n.charCodeAt(t)););return t}function d(n){return Bn[n]}function m(_){function $n(n){if(h(n)&&!(Io(n)||n instanceof zn)){if(n instanceof Bn)return n;if(Ke.call(n,"__chain__")&&Ke.call(n,"__wrapped__"))return Fr(n)}return new Bn(n)}function Ln(){}function Bn(n,t,r){this.__wrapped__=n,this.__actions__=r||[],
this.__chain__=!!t}function zn(n){this.__wrapped__=n,this.__actions__=null,this.__dir__=1,this.__filtered__=false,this.__iteratees__=null,this.__takeCount__=ju,this.__views__=null}function Mn(){this.__data__={}}function Dn(n){var t=n?n.length:0;for(this.data={hash:_u(null),set:new iu};t--;)this.push(n[t])}function Pn(n,t){var r=n.data;return(typeof t=="string"||ae(t)?r.set.has(t):r.hash[t])?0:-1}function qn(n,t){var r=-1,e=n.length;for(t||(t=Ce(e));++r<e;)t[r]=n[r];return t}function Kn(n,t){for(var r=-1,e=n.length;++r<e&&false!==t(n[r],r,n););
return n}function Vn(n,t){for(var r=-1,e=n.length;++r<e;)if(!t(n[r],r,n))return false;return true}function Gn(n,t){for(var r=-1,e=n.length,u=-1,o=[];++r<e;){var i=n[r];t(i,r,n)&&(o[++u]=i)}return o}function Jn(n,t){for(var r=-1,e=n.length,u=Ce(e);++r<e;)u[r]=t(n[r],r,n);return u}function Xn(n){for(var t=-1,r=n.length,e=Au;++t<r;){var u=n[t];u>e&&(e=u)}return e}function Hn(n,t){for(var r=-1,e=n.length;++r<e;)if(t(n[r],r,n))return true;return false}function Qn(n,t){return n===w?t:n}function nt(n,t,r,e){return n!==w&&Ke.call(e,r)?n:t;
}function tt(n,t,r){var e=zo(t);eu.apply(e,qu(t));for(var u=-1,o=e.length;++u<o;){var i=e[u],f=n[i],a=r(f,t[i],i,n,t);(a===a?a===f:f!==f)&&(f!==w||i in n)||(n[i]=a)}return n}function rt(n,t){for(var r=-1,e=n.length,u=Er(e),o=t.length,i=Ce(o);++r<o;){var f=t[r];i[r]=u?Ar(f,e)?n[f]:w:n[f]}return i}function et(n,t,r){r||(r={});for(var e=-1,u=t.length;++e<u;){var o=t[e];r[o]=n[o]}return r}function ut(n,t,r){var e=typeof n;return"function"==e?t===w?n:Bt(n,t,r):null==n?Oe:"object"==e?wt(n):t===w?Re(n):bt(n,t);
}function ot(n,t,r,e,u,o,i){var f;if(r&&(f=u?r(n,e,u):r(n)),f!==w)return f;if(!ae(n))return n;if(e=Io(n)){if(f=mr(n),!t)return qn(n,f)}else{var a=Ye.call(n),c=a==K;if(a!=Y&&a!=z&&(!c||u))return Nn[a]?br(n,a,t):u?n:{};if(f=wr(c?{}:n),!t)return Tu(f,n)}for(o||(o=[]),i||(i=[]),u=o.length;u--;)if(o[u]==n)return i[u];return o.push(n),i.push(f),(e?Kn:ht)(n,function(e,u){f[u]=ot(e,t,r,u,n,o,i)}),f}function it(n,t,r){if(typeof n!="function")throw new Be(L);return fu(function(){n.apply(w,r)},t)}function ft(n,t){
var e=n?n.length:0,u=[];if(!e)return u;var o=-1,i=dr(),f=i==r,a=f&&200<=t.length?zu(t):null,c=t.length;a&&(i=Pn,f=false,t=a);n:for(;++o<e;)if(a=n[o],f&&a===a){for(var l=c;l--;)if(t[l]===a)continue n;u.push(a)}else 0>i(t,a,0)&&u.push(a);return u}function at(n,t){var r=true;return Nu(n,function(n,e,u){return r=!!t(n,e,u)}),r}function ct(n,t){var r=[];return Nu(n,function(n,e,u){t(n,e,u)&&r.push(n)}),r}function lt(n,t,r,e){var u;return r(n,function(n,r,o){return t(n,r,o)?(u=e?r:n,false):void 0}),u}function st(n,t,r){
for(var e=-1,u=n.length,o=-1,i=[];++e<u;){var f=n[e];if(h(f)&&Er(f.length)&&(Io(f)||oe(f))){t&&(f=st(f,t,r));var a=-1,c=f.length;for(i.length+=c;++a<c;)i[++o]=f[a]}else r||(i[++o]=f)}return i}function pt(n,t){$u(n,t,ge)}function ht(n,t){return $u(n,t,zo)}function _t(n,t){return Lu(n,t,zo)}function vt(n,t){for(var r=-1,e=t.length,u=-1,o=[];++r<e;){var i=t[r];Co(n[i])&&(o[++u]=i)}return o}function gt(n,t,r){if(null!=n){r!==w&&r in Ur(n)&&(t=[r]),r=-1;for(var e=t.length;null!=n&&++r<e;)var u=n=n[t[r]];
return u}}function yt(n,t,r,e,u,o){if(n===t)return 0!==n||1/n==1/t;var i=typeof n,f=typeof t;if("function"!=i&&"object"!=i&&"function"!=f&&"object"!=f||null==n||null==t)n=n!==n&&t!==t;else n:{var i=yt,f=Io(n),a=Io(t),c=M,l=M;f||(c=Ye.call(n),c==z?c=Y:c!=Y&&(f=he(n))),a||(l=Ye.call(t),l==z?l=Y:l!=Y&&he(t));var s=c==Y,a=l==Y,l=c==l;if(!l||f||s){if(!e&&(c=s&&Ke.call(n,"__wrapped__"),a=a&&Ke.call(t,"__wrapped__"),c||a)){n=i(c?n.value():n,a?t.value():t,r,e,u,o);break n}if(l){for(u||(u=[]),o||(o=[]),c=u.length;c--;)if(u[c]==n){
n=o[c]==t;break n}u.push(n),o.push(t),n=(f?hr:vr)(n,t,i,r,e,u,o),u.pop(),o.pop()}else n=false}else n=_r(n,t,c)}return n}function dt(n,t,r,e,u){for(var o=-1,i=t.length,f=!u;++o<i;)if(f&&e[o]?r[o]!==n[t[o]]:!(t[o]in n))return false;for(o=-1;++o<i;){var a=t[o],c=n[a],l=r[o];if(f&&e[o]?a=c!==w||a in n:(a=u?u(c,l,a):w,a===w&&(a=yt(l,c,u,true))),!a)return false}return true}function mt(n,t){var r=-1,e=Pu(n),u=Er(e)?Ce(e):[];return Nu(n,function(n,e,o){u[++r]=t(n,e,o)}),u}function wt(n){var t=zo(n),r=t.length;if(!r)return ke(true);
if(1==r){var e=t[0],u=n[e];if(Ir(u))return function(n){return null==n?false:n[e]===u&&(u!==w||e in Ur(n))}}for(var o=Ce(r),i=Ce(r);r--;)u=n[t[r]],o[r]=u,i[r]=Ir(u);return function(n){return null!=n&&dt(Ur(n),t,o,i)}}function bt(n,t){var r=Io(n),e=kr(n)&&Ir(t),u=n+"";return n=Nr(n),function(o){if(null==o)return false;var i=u;if(o=Ur(o),!(!r&&e||i in o)){if(o=1==n.length?o:gt(o,It(n,0,-1)),null==o)return false;i=Mr(n),o=Ur(o)}return o[i]===t?t!==w||i in o:yt(t,o[i],null,true)}}function xt(n,t,r,e,u){if(!ae(n))return n;
var o=Er(t.length)&&(Io(t)||he(t));if(!o){var i=zo(t);eu.apply(i,qu(t))}return Kn(i||t,function(f,a){if(i&&(a=f,f=t[a]),h(f)){e||(e=[]),u||(u=[]);n:{for(var c=a,l=e,s=u,p=l.length,_=t[c];p--;)if(l[p]==_){n[c]=s[p];break n}var p=n[c],v=r?r(p,_,c,n,t):w,g=v===w;g&&(v=_,Er(_.length)&&(Io(_)||he(_))?v=Io(p)?p:Pu(p)?qn(p):[]:So(_)||oe(_)?v=oe(p)?_e(p):So(p)?p:{}:g=false),l.push(_),s.push(v),g?n[c]=xt(v,_,r,l,s):(v===v?v!==p:p===p)&&(n[c]=v)}}else c=n[a],l=r?r(c,f,a,n,t):w,(s=l===w)&&(l=f),!o&&l===w||!s&&(l===l?l===c:c!==c)||(n[a]=l);
}),n}function At(n){return function(t){return null==t?w:t[n]}}function jt(n){var t=n+"";return n=Nr(n),function(r){return gt(r,n,t)}}function kt(n,t){for(var r=t.length;r--;){var e=parseFloat(t[r]);if(e!=u&&Ar(e)){var u=e;au.call(n,e,1)}}}function Ot(n,t){return n+nu(xu()*(t-n+1))}function Et(n,t,r,e,u){return u(n,function(n,u,o){r=e?(e=false,n):t(r,n,u,o)}),r}function It(n,t,r){var e=-1,u=n.length;for(t=null==t?0:+t||0,0>t&&(t=-t>u?0:u+t),r=r===w||r>u?u:+r||0,0>r&&(r+=u),u=t>r?0:r-t>>>0,t>>>=0,r=Ce(u);++e<u;)r[e]=n[e+t];
return r}function Rt(n,t){var r;return Nu(n,function(n,e,u){return r=t(n,e,u),!r}),!!r}function Ct(n,t){var r=n.length;for(n.sort(t);r--;)n[r]=n[r].c;return n}function St(t,r,e){var u=yr(),o=-1;return r=Jn(r,function(n){return u(n)}),t=mt(t,function(n){return{a:Jn(r,function(t){return t(n)}),b:++o,c:n}}),Ct(t,function(t,r){var u;n:{u=-1;for(var o=t.a,i=r.a,f=o.length,a=e.length;++u<f;){var c=n(o[u],i[u]);if(c){u=u<a?c*(e[u]?1:-1):c;break n}}u=t.b-r.b}return u})}function Wt(n,t){var r=0;return Nu(n,function(n,e,u){
r+=+t(n,e,u)||0}),r}function Tt(n,t){var e=-1,u=dr(),o=n.length,i=u==r,f=i&&200<=o,a=f?zu():null,c=[];a?(u=Pn,i=false):(f=false,a=t?[]:c);n:for(;++e<o;){var l=n[e],s=t?t(l,e,n):l;if(i&&l===l){for(var p=a.length;p--;)if(a[p]===s)continue n;t&&a.push(s),c.push(l)}else 0>u(a,s,0)&&((t||f)&&a.push(s),c.push(l))}return c}function Ut(n,t){for(var r=-1,e=t.length,u=Ce(e);++r<e;)u[r]=n[t[r]];return u}function Nt(n,t,r,e){for(var u=n.length,o=e?u:-1;(e?o--:++o<u)&&t(n[o],o,n););return r?It(n,e?0:o,e?o+1:u):It(n,e?o+1:0,e?u:o);
}function Ft(n,t){var r=n;r instanceof zn&&(r=r.value());for(var e=-1,u=t.length;++e<u;){var r=[r],o=t[e];eu.apply(r,o.args),r=o.func.apply(o.thisArg,r)}return r}function $t(n,t,r){var e=0,u=n?n.length:e;if(typeof t=="number"&&t===t&&u<=Eu){for(;e<u;){var o=e+u>>>1,i=n[o];(r?i<=t:i<t)?e=o+1:u=o}return u}return Lt(n,t,Oe,r)}function Lt(n,t,r,e){t=r(t);for(var u=0,o=n?n.length:0,i=t!==t,f=t===w;u<o;){var a=nu((u+o)/2),c=r(n[a]),l=c===c;(i?l||e:f?l&&(e||c!==w):e?c<=t:c<t)?u=a+1:o=a}return du(o,Ou)}function Bt(n,t,r){
if(typeof n!="function")return Oe;if(t===w)return n;switch(r){case 1:return function(r){return n.call(t,r)};case 3:return function(r,e,u){return n.call(t,r,e,u)};case 4:return function(r,e,u,o){return n.call(t,r,e,u,o)};case 5:return function(r,e,u,o,i){return n.call(t,r,e,u,o,i)}}return function(){return n.apply(t,arguments)}}function zt(n){return Xe.call(n,0)}function Mt(n,t,r){for(var e=r.length,u=-1,o=yu(n.length-e,0),i=-1,f=t.length,a=Ce(o+f);++i<f;)a[i]=t[i];for(;++u<e;)a[r[u]]=n[u];for(;o--;)a[i++]=n[u++];
return a}function Dt(n,t,r){for(var e=-1,u=r.length,o=-1,i=yu(n.length-u,0),f=-1,a=t.length,c=Ce(i+a);++o<i;)c[o]=n[o];for(i=o;++f<a;)c[i+f]=t[f];for(;++e<u;)c[i+r[e]]=n[o++];return c}function Pt(n,t){return function(r,e,u){var o=t?t():{};if(e=yr(e,u,3),Io(r)){u=-1;for(var i=r.length;++u<i;){var f=r[u];n(o,f,e(f,u,r),r)}}else Nu(r,function(t,r,u){n(o,t,e(t,r,u),u)});return o}}function qt(n){return ue(function(t,r){var e=-1,u=null==t?0:r.length,o=2<u&&r[u-2],i=2<u&&r[2],f=1<u&&r[u-1];for(typeof o=="function"?(o=Bt(o,f,5),
u-=2):(o=typeof f=="function"?f:null,u-=o?1:0),i&&jr(r[0],r[1],i)&&(o=3>u?null:o,u=1);++e<u;)(i=r[e])&&n(t,i,o);return t})}function Kt(n,t){return function(r,e){var u=r?Pu(r):0;if(!Er(u))return n(r,e);for(var o=t?u:-1,i=Ur(r);(t?o--:++o<u)&&false!==e(i[o],o,i););return r}}function Vt(n){return function(t,r,e){var u=Ur(t);e=e(t);for(var o=e.length,i=n?o:-1;n?i--:++i<o;){var f=e[i];if(false===r(u[f],f,u))break}return t}}function Yt(n,t){function r(){return(this&&this!==Yn&&this instanceof r?e:n).apply(t,arguments);
}var e=Gt(n);return r}function Zt(n){return function(t){var r=-1;t=Ae(de(t));for(var e=t.length,u="";++r<e;)u=n(u,t[r],r);return u}}function Gt(n){return function(){var t=Uu(n.prototype),r=n.apply(t,arguments);return ae(r)?r:t}}function Jt(n){function t(r,e,u){return u&&jr(r,e,u)&&(e=null),r=pr(r,n,null,null,null,null,null,e),r.placeholder=t.placeholder,r}return t}function Xt(n,t){return function(r,e,u){u&&jr(r,e,u)&&(e=null);var i=yr(),f=null==e;if(i===ut&&f||(f=false,e=i(e,u,3)),f){if(e=Io(r),e||!pe(r))return n(e?r:Tr(r));
e=o}return gr(r,e,t)}}function Ht(n,r){return function(e,u,o){return u=yr(u,o,3),Io(e)?(u=t(e,u,r),-1<u?e[u]:w):lt(e,u,n)}}function Qt(n){return function(r,e,u){return r&&r.length?(e=yr(e,u,3),t(r,e,n)):-1}}function nr(n){return function(t,r,e){return r=yr(r,e,3),lt(t,r,n,true)}}function tr(n){return function(){var t=arguments.length;if(!t)return function(){return arguments[0]};for(var r,e=n?t:-1,u=0,o=Ce(t);n?e--:++e<t;){var i=o[u++]=arguments[e];if(typeof i!="function")throw new Be(L);var f=r?"":Du(i);
r="wrapper"==f?new Bn([]):r}for(e=r?-1:t;++e<t;)i=o[e],f=Du(i),r=(u="wrapper"==f?Mu(i):null)&&Or(u[0])?r[Du(u[0])].apply(r,u[3]):1==i.length&&Or(i)?r[f]():r.thru(i);return function(){var n=arguments;if(r&&1==n.length&&Io(n[0]))return r.plant(n[0]).value();for(var e=0,n=o[e].apply(this,n);++e<t;)n=o[e].call(this,n);return n}}}function rr(n,t){return function(r,e,u){return typeof e=="function"&&u===w&&Io(r)?n(r,e):t(r,Bt(e,u,3))}}function er(n){return function(t,r,e){return(typeof r!="function"||e!==w)&&(r=Bt(r,e,3)),
n(t,r,ge)}}function ur(n){return function(t,r,e){return(typeof r!="function"||e!==w)&&(r=Bt(r,e,3)),n(t,r)}}function or(n){return function(t,r,e){return(t=u(t))&&(n?t:"")+cr(t,r,e)+(n?"":t)}}function ir(n){var t=ue(function(r,e){var u=v(e,t.placeholder);return pr(r,n,null,e,u)});return t}function fr(n,t){return function(r,e,u,o){var i=3>arguments.length;return typeof e=="function"&&o===w&&Io(r)?n(r,e,u,i):Et(r,yr(e,o,4),u,i,t)}}function ar(n,t,r,e,u,o,i,f,a,c){function l(){for(var b=arguments.length,j=b,k=Ce(b);j--;)k[j]=arguments[j];
if(e&&(k=Mt(k,e,u)),o&&(k=Dt(k,o,i)),_||y){var j=l.placeholder,O=v(k,j),b=b-O.length;if(b<c){var R=f?qn(f):null,b=yu(c-b,0),C=_?O:null,O=_?null:O,S=_?k:null,k=_?null:k;return t|=_?E:I,t&=~(_?I:E),g||(t&=~(x|A)),k=[n,t,r,S,C,k,O,R,a,b],R=ar.apply(w,k),Or(n)&&Ku(R,k),R.placeholder=j,R}}if(j=p?r:this,h&&(n=j[m]),f)for(R=k.length,b=du(f.length,R),C=qn(k);b--;)O=f[b],k[b]=Ar(O,R)?C[O]:w;return s&&a<k.length&&(k.length=a),(this&&this!==Yn&&this instanceof l?d||Gt(n):n).apply(j,k)}var s=t&R,p=t&x,h=t&A,_=t&k,g=t&j,y=t&O,d=!h&&Gt(n),m=n;
return l}function cr(n,t,r){return n=n.length,t=+t,n<t&&vu(t)?(t-=n,r=null==r?" ":r+"",be(r,He(t/r.length)).slice(0,t)):""}function lr(n,t,r,e){function u(){for(var t=-1,f=arguments.length,a=-1,c=e.length,l=Ce(f+c);++a<c;)l[a]=e[a];for(;f--;)l[a++]=arguments[++t];return(this&&this!==Yn&&this instanceof u?i:n).apply(o?r:this,l)}var o=t&x,i=Gt(n);return u}function sr(n){return function(t,r,e,u){var o=yr(e);return o===ut&&null==e?$t(t,r,n):Lt(t,r,o(e,u,1),n)}}function pr(n,t,r,e,u,o,i,f){var a=t&A;if(!a&&typeof n!="function")throw new Be(L);
var c=e?e.length:0;if(c||(t&=~(E|I),e=u=null),c-=u?u.length:0,t&I){var l=e,s=u;e=u=null}var p=a?null:Mu(n);return r=[n,t,r,e,u,l,s,o,i,f],p&&(e=r[1],t=p[1],f=e|t,u=t==R&&e==k||t==R&&e==C&&r[7].length<=p[8]||t==(R|C)&&e==k,(f<R||u)&&(t&x&&(r[2]=p[2],f|=e&x?0:j),(e=p[3])&&(u=r[3],r[3]=u?Mt(u,e,p[4]):qn(e),r[4]=u?v(r[3],B):qn(p[4])),(e=p[5])&&(u=r[5],r[5]=u?Dt(u,e,p[6]):qn(e),r[6]=u?v(r[5],B):qn(p[6])),(e=p[7])&&(r[7]=qn(e)),t&R&&(r[8]=null==r[8]?p[8]:du(r[8],p[8])),null==r[9]&&(r[9]=p[9]),r[0]=p[0],
r[1]=f),t=r[1],f=r[9]),r[9]=null==f?a?0:n.length:yu(f-c,0)||0,(p?Bu:Ku)(t==x?Yt(r[0],r[2]):t!=E&&t!=(x|E)||r[4].length?ar.apply(w,r):lr.apply(w,r),r)}function hr(n,t,r,e,u,o,i){var f=-1,a=n.length,c=t.length,l=true;if(a!=c&&(!u||c<=a))return false;for(;l&&++f<a;){var s=n[f],p=t[f],l=w;if(e&&(l=u?e(p,s,f):e(s,p,f)),l===w)if(u)for(var h=c;h--&&(p=t[h],!(l=s&&s===p||r(s,p,e,u,o,i))););else l=s&&s===p||r(s,p,e,u,o,i)}return!!l}function _r(n,t,r){switch(r){case D:case P:return+n==+t;case q:return n.name==t.name&&n.message==t.message;
case V:return n!=+n?t!=+t:0==n?1/n==1/t:n==+t;case Z:case G:return n==t+""}return false}function vr(n,t,r,e,u,o,i){var f=zo(n),a=f.length,c=zo(t).length;if(a!=c&&!u)return false;for(var c=u,l=-1;++l<a;){var s=f[l],p=u?s in t:Ke.call(t,s);if(p){var h=n[s],_=t[s],p=w;e&&(p=u?e(_,h,s):e(h,_,s)),p===w&&(p=h&&h===_||r(h,_,e,u,o,i))}if(!p)return false;c||(c="constructor"==s)}return c||(r=n.constructor,e=t.constructor,!(r!=e&&"constructor"in n&&"constructor"in t)||typeof r=="function"&&r instanceof r&&typeof e=="function"&&e instanceof e)?true:false;
}function gr(n,t,r){var e=r?ju:Au,u=e,o=u;return Nu(n,function(n,i,f){i=t(n,i,f),((r?i<u:i>u)||i===e&&i===o)&&(u=i,o=n)}),o}function yr(n,t,r){var e=$n.callback||je,e=e===je?ut:e;return r?e(n,t,r):e}function dr(n,t,e){var u=$n.indexOf||zr,u=u===zr?r:u;return n?u(n,t,e):u}function mr(n){var t=n.length,r=new n.constructor(t);return t&&"string"==typeof n[0]&&Ke.call(n,"index")&&(r.index=n.index,r.input=n.input),r}function wr(n){return n=n.constructor,typeof n=="function"&&n instanceof n||(n=Fe),new n;
}function br(n,t,r){var e=n.constructor;switch(t){case J:return zt(n);case D:case P:return new e(+n);case X:case H:case Q:case nn:case tn:case rn:case en:case un:case on:return t=n.buffer,new e(r?zt(t):t,n.byteOffset,n.length);case V:case G:return new e(n);case Z:var u=new e(n.source,kn.exec(n));u.lastIndex=n.lastIndex}return u}function xr(n,t,r){return null==n||kr(t,n)||(t=Nr(t),n=1==t.length?n:gt(n,It(t,0,-1)),t=Mr(t)),t=null==n?n:n[t],null==t?w:t.apply(n,r)}function Ar(n,t){return n=+n,t=null==t?Ru:t,
-1<n&&0==n%1&&n<t}function jr(n,t,r){if(!ae(r))return false;var e=typeof t;return"number"==e?(e=Pu(r),e=Er(e)&&Ar(t,e)):e="string"==e&&t in r,e?(t=r[t],n===n?n===t:t!==t):false}function kr(n,t){var r=typeof n;return"string"==r&&dn.test(n)||"number"==r?true:Io(n)?false:!yn.test(n)||null!=t&&n in Ur(t)}function Or(n){var t=Du(n);return!!t&&n===$n[t]&&t in zn.prototype}function Er(n){return typeof n=="number"&&-1<n&&0==n%1&&n<=Ru}function Ir(n){return n===n&&(0===n?0<1/n:!ae(n))}function Rr(n,t){n=Ur(n);for(var r=-1,e=t.length,u={};++r<e;){
var o=t[r];o in n&&(u[o]=n[o])}return u}function Cr(n,t){var r={};return pt(n,function(n,e,u){t(n,e,u)&&(r[e]=n)}),r}function Sr(n){var t;if(!h(n)||Ye.call(n)!=Y||!(Ke.call(n,"constructor")||(t=n.constructor,typeof t!="function"||t instanceof t)))return false;var r;return pt(n,function(n,t){r=t}),r===w||Ke.call(n,r)}function Wr(n){for(var t=ge(n),r=t.length,e=r&&n.length,u=$n.support,u=e&&Er(e)&&(Io(n)||u.nonEnumArgs&&oe(n)),o=-1,i=[];++o<r;){var f=t[o];(u&&Ar(f,e)||Ke.call(n,f))&&i.push(f)}return i}
function Tr(n){return null==n?[]:Er(Pu(n))?ae(n)?n:Fe(n):ye(n)}function Ur(n){return ae(n)?n:Fe(n)}function Nr(n){if(Io(n))return n;var t=[];return u(n).replace(mn,function(n,r,e,u){t.push(e?u.replace(An,"$1"):r||n)}),t}function Fr(n){return n instanceof zn?n.clone():new Bn(n.__wrapped__,n.__chain__,qn(n.__actions__))}function $r(n,t,r){return n&&n.length?((r?jr(n,t,r):null==t)&&(t=1),It(n,0>t?0:t)):[]}function Lr(n,t,r){var e=n?n.length:0;return e?((r?jr(n,t,r):null==t)&&(t=1),t=e-(+t||0),It(n,0,0>t?0:t)):[];
}function Br(n){return n?n[0]:w}function zr(n,t,e){var u=n?n.length:0;if(!u)return-1;if(typeof e=="number")e=0>e?yu(u+e,0):e;else if(e)return e=$t(n,t),n=n[e],(t===t?t===n:n!==n)?e:-1;return r(n,t,e||0)}function Mr(n){var t=n?n.length:0;return t?n[t-1]:w}function Dr(n){return $r(n,1)}function Pr(n,t,e,u){if(!n||!n.length)return[];null!=t&&typeof t!="boolean"&&(u=e,e=jr(n,t,u)?null:t,t=false);var o=yr();if((o!==ut||null!=e)&&(e=o(e,u,3)),t&&dr()==r){t=e;var i;e=-1,u=n.length;for(var o=-1,f=[];++e<u;){
var a=n[e],c=t?t(a,e,n):a;e&&i===c||(i=c,f[++o]=a)}n=f}else n=Tt(n,e);return n}function qr(n){for(var t=-1,r=(n&&n.length&&Xn(Jn(n,Pu)))>>>0,e=Ce(r);++t<r;)e[t]=Jn(n,At(t));return e}function Kr(n,t){var r=-1,e=n?n.length:0,u={};for(!e||t||Io(n[0])||(t=[]);++r<e;){var o=n[r];t?u[o]=t[r]:o&&(u[o[0]]=o[1])}return u}function Vr(n){return n=$n(n),n.__chain__=true,n}function Yr(n,t,r){return t.call(r,n)}function Zr(n,t,r){var e=Io(n)?Vn:at;return r&&jr(n,t,r)&&(t=null),(typeof t!="function"||r!==w)&&(t=yr(t,r,3)),
e(n,t)}function Gr(n,t,r){var e=Io(n)?Gn:ct;return t=yr(t,r,3),e(n,t)}function Jr(n,t,r,e){var u=n?Pu(n):0;return Er(u)||(n=ye(n),u=n.length),u?(r=typeof r!="number"||e&&jr(t,r,e)?0:0>r?yu(u+r,0):r||0,typeof n=="string"||!Io(n)&&pe(n)?r<u&&-1<n.indexOf(t,r):-1<dr(n,t,r)):false}function Xr(n,t,r){var e=Io(n)?Jn:mt;return t=yr(t,r,3),e(n,t)}function Hr(n,t,r){return(r?jr(n,t,r):null==t)?(n=Tr(n),t=n.length,0<t?n[Ot(0,t-1)]:w):(n=Qr(n),n.length=du(0>t?0:+t||0,n.length),n)}function Qr(n){n=Tr(n);for(var t=-1,r=n.length,e=Ce(r);++t<r;){
var u=Ot(0,t);t!=u&&(e[t]=e[u]),e[u]=n[t]}return e}function ne(n,t,r){var e=Io(n)?Hn:Rt;return r&&jr(n,t,r)&&(t=null),(typeof t!="function"||r!==w)&&(t=yr(t,r,3)),e(n,t)}function te(n,t){var r;if(typeof t!="function"){if(typeof n!="function")throw new Be(L);var e=n;n=t,t=e}return function(){return 0<--n&&(r=t.apply(this,arguments)),1>=n&&(t=null),r}}function re(n,t,r){function e(){var r=t-(_o()-c);0>=r||r>t?(f&&Qe(f),r=p,f=s=p=w,r&&(h=_o(),a=n.apply(l,i),s||f||(i=l=null))):s=fu(e,r)}function u(){
s&&Qe(s),f=s=p=w,(v||_!==t)&&(h=_o(),a=n.apply(l,i),s||f||(i=l=null))}function o(){if(i=arguments,c=_o(),l=this,p=v&&(s||!g),false===_)var r=g&&!s;else{f||g||(h=c);var o=_-(c-h),y=0>=o||o>_;y?(f&&(f=Qe(f)),h=c,a=n.apply(l,i)):f||(f=fu(u,o))}return y&&s?s=Qe(s):s||t===_||(s=fu(e,t)),r&&(y=true,a=n.apply(l,i)),!y||s||f||(i=l=null),a}var i,f,a,c,l,s,p,h=0,_=false,v=true;if(typeof n!="function")throw new Be(L);if(t=0>t?0:+t||0,true===r)var g=true,v=false;else ae(r)&&(g=r.leading,_="maxWait"in r&&yu(+r.maxWait||0,t),v="trailing"in r?r.trailing:v);
return o.cancel=function(){s&&Qe(s),f&&Qe(f),f=s=p=w},o}function ee(n,t){function r(){var e=arguments,u=r.cache,o=t?t.apply(this,e):e[0];return u.has(o)?u.get(o):(e=n.apply(this,e),u.set(o,e),e)}if(typeof n!="function"||t&&typeof t!="function")throw new Be(L);return r.cache=new ee.Cache,r}function ue(n,t){if(typeof n!="function")throw new Be(L);return t=yu(t===w?n.length-1:+t||0,0),function(){for(var r=arguments,e=-1,u=yu(r.length-t,0),o=Ce(u);++e<u;)o[e]=r[t+e];switch(t){case 0:return n.call(this,o);
case 1:return n.call(this,r[0],o);case 2:return n.call(this,r[0],r[1],o)}for(u=Ce(t+1),e=-1;++e<t;)u[e]=r[e];return u[t]=o,n.apply(this,u)}}function oe(n){return Er(h(n)?n.length:w)&&Ye.call(n)==z}function ie(n){return!!n&&1===n.nodeType&&h(n)&&-1<Ye.call(n).indexOf("Element")}function fe(n){return h(n)&&typeof n.message=="string"&&Ye.call(n)==q}function ae(n){var t=typeof n;return"function"==t||!!n&&"object"==t}function ce(n){return null==n?false:Ye.call(n)==K?Ge.test(qe.call(n)):h(n)&&En.test(n)}function le(n){
return typeof n=="number"||h(n)&&Ye.call(n)==V}function se(n){return h(n)&&Ye.call(n)==Z||false}function pe(n){return typeof n=="string"||h(n)&&Ye.call(n)==G}function he(n){return h(n)&&Er(n.length)&&!!Un[Ye.call(n)]}function _e(n){return et(n,ge(n))}function ve(n){return vt(n,ge(n))}function ge(n){if(null==n)return[];ae(n)||(n=Fe(n));for(var t=n.length,t=t&&Er(t)&&(Io(n)||Wu.nonEnumArgs&&oe(n))&&t||0,r=n.constructor,e=-1,r=typeof r=="function"&&r.prototype===n,u=Ce(t),o=0<t;++e<t;)u[e]=e+"";for(var i in n)o&&Ar(i,t)||"constructor"==i&&(r||!Ke.call(n,i))||u.push(i);
return u}function ye(n){return Ut(n,zo(n))}function de(n){return(n=u(n))&&n.replace(In,c).replace(xn,"")}function me(n){return(n=u(n))&&bn.test(n)?n.replace(wn,"\\$&"):n}function we(n,t,r){return r&&jr(n,t,r)&&(t=0),bu(n,t)}function be(n,t){var r="";if(n=u(n),t=+t,1>t||!n||!vu(t))return r;do t%2&&(r+=n),t=nu(t/2),n+=n;while(t);return r}function xe(n,t,r){var e=n;return(n=u(n))?(r?jr(e,t,r):null==t)?n.slice(g(n),y(n)+1):(t+="",n.slice(i(n,t),f(n,t)+1)):n}function Ae(n,t,r){return r&&jr(n,t,r)&&(t=null),
n=u(n),n.match(t||Sn)||[]}function je(n,t,r){return r&&jr(n,t,r)&&(t=null),ut(n,t)}function ke(n){return function(){return n}}function Oe(n){return n}function Ee(n,t,r){if(null==r){var e=ae(t),u=e&&zo(t);((u=u&&u.length&&vt(t,u))?u.length:e)||(u=false,r=t,t=n,n=this)}u||(u=vt(t,zo(t)));var o=true,e=-1,i=Co(n),f=u.length;false===r?o=false:ae(r)&&"chain"in r&&(o=r.chain);for(;++e<f;){r=u[e];var a=t[r];n[r]=a,i&&(n.prototype[r]=function(t){return function(){var r=this.__chain__;if(o||r){var e=n(this.__wrapped__);
return(e.__actions__=qn(this.__actions__)).push({func:t,args:arguments,thisArg:n}),e.__chain__=r,e}return r=[this.value()],eu.apply(r,arguments),t.apply(n,r)}}(a))}return n}function Ie(){}function Re(n){return kr(n)?At(n):jt(n)}_=_?Zn.defaults(Yn.Object(),_,Zn.pick(Yn,Tn)):Yn;var Ce=_.Array,Se=_.Date,We=_.Error,Te=_.Function,Ue=_.Math,Ne=_.Number,Fe=_.Object,$e=_.RegExp,Le=_.String,Be=_.TypeError,ze=Ce.prototype,Me=Fe.prototype,De=Le.prototype,Pe=(Pe=_.window)&&Pe.document,qe=Te.prototype.toString,Ke=Me.hasOwnProperty,Ve=0,Ye=Me.toString,Ze=_._,Ge=$e("^"+me(Ye).replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Je=ce(Je=_.ArrayBuffer)&&Je,Xe=ce(Xe=Je&&new Je(0).slice)&&Xe,He=Ue.ceil,Qe=_.clearTimeout,nu=Ue.floor,tu=ce(tu=Fe.getOwnPropertySymbols)&&tu,ru=ce(ru=Fe.getPrototypeOf)&&ru,eu=ze.push,uu=ce(Fe.preventExtensions=Fe.preventExtensions)&&uu,ou=Me.propertyIsEnumerable,iu=ce(iu=_.Set)&&iu,fu=_.setTimeout,au=ze.splice,cu=ce(cu=_.Uint8Array)&&cu,lu=ce(lu=_.WeakMap)&&lu,su=function(){
try{var n=ce(n=_.Float64Array)&&n,t=new n(new Je(10),0,1)&&n}catch(r){}return t}(),pu=function(){var n={1:0},t=uu&&ce(t=Fe.assign)&&t;try{t(uu(n),"xo")}catch(r){}return!n[1]&&t}(),hu=ce(hu=Ce.isArray)&&hu,_u=ce(_u=Fe.create)&&_u,vu=_.isFinite,gu=ce(gu=Fe.keys)&&gu,yu=Ue.max,du=Ue.min,mu=ce(mu=Se.now)&&mu,wu=ce(wu=Ne.isFinite)&&wu,bu=_.parseInt,xu=Ue.random,Au=Ne.NEGATIVE_INFINITY,ju=Ne.POSITIVE_INFINITY,ku=Ue.pow(2,32)-1,Ou=ku-1,Eu=ku>>>1,Iu=su?su.BYTES_PER_ELEMENT:0,Ru=Ue.pow(2,53)-1,Cu=lu&&new lu,Su={},Wu=$n.support={};
!function(n){function t(){this.x=n}var r=[];t.prototype={valueOf:n,y:n};for(var e in new t)r.push(e);Wu.funcDecomp=/\bthis\b/.test(function(){return this}),Wu.funcNames=typeof Te.name=="string";try{Wu.dom=11===Pe.createDocumentFragment().nodeType}catch(u){Wu.dom=false}try{Wu.nonEnumArgs=!ou.call(arguments,1)}catch(o){Wu.nonEnumArgs=true}}(1,0),$n.templateSettings={escape:_n,evaluate:vn,interpolate:gn,variable:"",imports:{_:$n}};var Tu=pu||function(n,t){return null==t?n:et(t,qu(t),et(t,zo(t),n))},Uu=function(){
function n(){}return function(t){if(ae(t)){n.prototype=t;var r=new n;n.prototype=null}return r||_.Object()}}(),Nu=Kt(ht),Fu=Kt(_t,true),$u=Vt(),Lu=Vt(true),Bu=Cu?function(n,t){return Cu.set(n,t),n}:Oe;Xe||(zt=Je&&cu?function(n){var t=n.byteLength,r=su?nu(t/Iu):0,e=r*Iu,u=new Je(t);if(r){var o=new su(u,0,r);o.set(new su(n,0,r))}return t!=e&&(o=new cu(u,e),o.set(new cu(n,e))),u}:ke(null));var zu=_u&&iu?function(n){return new Dn(n)}:ke(null),Mu=Cu?function(n){return Cu.get(n)}:Ie,Du=function(){return Wu.funcNames?"constant"==ke.name?At("name"):function(n){
for(var t=n.name,r=Su[t],e=r?r.length:0;e--;){var u=r[e],o=u.func;if(null==o||o==n)return u.name}return t}:ke("")}(),Pu=At("length"),qu=tu?function(n){return tu(Ur(n))}:ke([]),Ku=function(){var n=0,t=0;return function(r,e){var u=_o(),o=U-(u-t);if(t=u,0<o){if(++n>=T)return r}else n=0;return Bu(r,e)}}(),Vu=ue(function(n,t){return Io(n)||oe(n)?ft(n,st(t,false,true)):[]}),Yu=Qt(),Zu=Qt(true),Gu=ue(function(t,r){t||(t=[]),r=st(r);var e=rt(t,r);return kt(t,r.sort(n)),e}),Ju=sr(),Xu=sr(true),Hu=ue(function(n){return Tt(st(n,false,true));
}),Qu=ue(function(n,t){return Io(n)||oe(n)?ft(n,t):[]}),no=ue(qr),to=ue(function(n,t){var r=n?Pu(n):0;return Er(r)&&(n=Tr(n)),rt(n,st(t))}),ro=Pt(function(n,t,r){Ke.call(n,r)?++n[r]:n[r]=1}),eo=Ht(Nu),uo=Ht(Fu,true),oo=rr(Kn,Nu),io=rr(function(n,t){for(var r=n.length;r--&&false!==t(n[r],r,n););return n},Fu),fo=Pt(function(n,t,r){Ke.call(n,r)?n[r].push(t):n[r]=[t]}),ao=Pt(function(n,t,r){n[r]=t}),co=ue(function(n,t,r){var e=-1,u=typeof t=="function",o=kr(t),i=Pu(n),f=Er(i)?Ce(i):[];return Nu(n,function(n){
var i=u?t:o&&null!=n&&n[t];f[++e]=i?i.apply(n,r):xr(n,t,r)}),f}),lo=Pt(function(n,t,r){n[r?0:1].push(t)},function(){return[[],[]]}),so=fr(function(n,t,r,e){var u=-1,o=n.length;for(e&&o&&(r=n[++u]);++u<o;)r=t(r,n[u],u,n);return r},Nu),po=fr(function(n,t,r,e){var u=n.length;for(e&&u&&(r=n[--u]);u--;)r=t(r,n[u],u,n);return r},Fu),ho=ue(function(n,t){if(null==n)return[];var r=t[2];return r&&jr(t[0],t[1],r)&&(t.length=1),St(n,st(t),[])}),_o=mu||function(){return(new Se).getTime()},vo=ue(function(n,t,r){
var e=x;if(r.length)var u=v(r,vo.placeholder),e=e|E;return pr(n,e,t,r,u)}),go=ue(function(n,t){t=t.length?st(t):ve(n);for(var r=-1,e=t.length;++r<e;){var u=t[r];n[u]=pr(n[u],x,n)}return n}),yo=ue(function(n,t,r){var e=x|A;if(r.length)var u=v(r,yo.placeholder),e=e|E;return pr(t,e,n,r,u)}),mo=Jt(k),wo=Jt(O),bo=ue(function(n,t){return it(n,1,t)}),xo=ue(function(n,t,r){return it(n,t,r)}),Ao=tr(),jo=tr(true),ko=ir(E),Oo=ir(I),Eo=ue(function(n,t){return pr(n,C,null,null,null,st(t))}),Io=hu||function(n){return h(n)&&Er(n.length)&&Ye.call(n)==M;
};Wu.dom||(ie=function(n){return!!n&&1===n.nodeType&&h(n)&&!So(n)});var Ro=wu||function(n){return typeof n=="number"&&vu(n)},Co=e(/x/)||cu&&!e(cu)?function(n){return Ye.call(n)==K}:e,So=ru?function(n){if(!n||Ye.call(n)!=Y)return false;var t=n.valueOf,r=ce(t)&&(r=ru(t))&&ru(r);return r?n==r||ru(n)==r:Sr(n)}:Sr,Wo=qt(function(n,t,r){return r?tt(n,t,r):Tu(n,t)}),To=ue(function(n){var t=n[0];return null==t?t:(n.push(Qn),Wo.apply(w,n))}),Uo=nr(ht),No=nr(_t),Fo=er($u),$o=er(Lu),Lo=ur(ht),Bo=ur(_t),zo=gu?function(n){
if(n)var t=n.constructor,r=n.length;return typeof t=="function"&&t.prototype===n||typeof n!="function"&&Er(r)?Wr(n):ae(n)?gu(n):[]}:Wr,Mo=qt(xt),Do=ue(function(n,t){if(null==n)return{};if("function"!=typeof t[0])return t=Jn(st(t),Le),Rr(n,ft(ge(n),t));var r=Bt(t[0],t[1],3);return Cr(n,function(n,t,e){return!r(n,t,e)})}),Po=ue(function(n,t){return null==n?{}:"function"==typeof t[0]?Cr(n,Bt(t[0],t[1],3)):Rr(n,st(t))}),qo=Zt(function(n,t,r){return t=t.toLowerCase(),n+(r?t.charAt(0).toUpperCase()+t.slice(1):t);
}),Ko=Zt(function(n,t,r){return n+(r?"-":"")+t.toLowerCase()}),Vo=or(),Yo=or(true);8!=bu(Wn+"08")&&(we=function(n,t,r){return(r?jr(n,t,r):null==t)?t=0:t&&(t=+t),n=xe(n),bu(n,t||(On.test(n)?16:10))});var Zo=Zt(function(n,t,r){return n+(r?"_":"")+t.toLowerCase()}),Go=Zt(function(n,t,r){return n+(r?" ":"")+(t.charAt(0).toUpperCase()+t.slice(1))}),Jo=ue(function(n,t){try{return n.apply(w,t)}catch(r){return fe(r)?r:new We(r)}}),Xo=ue(function(n,t){return function(r){return xr(r,n,t)}}),Ho=ue(function(n,t){
return function(r){return xr(n,r,t)}}),Qo=Xt(Xn),ni=Xt(function(n){for(var t=-1,r=n.length,e=ju;++t<r;){var u=n[t];u<e&&(e=u)}return e},true);return $n.prototype=Ln.prototype,Bn.prototype=Uu(Ln.prototype),Bn.prototype.constructor=Bn,zn.prototype=Uu(Ln.prototype),zn.prototype.constructor=zn,Mn.prototype["delete"]=function(n){return this.has(n)&&delete this.__data__[n]},Mn.prototype.get=function(n){return"__proto__"==n?w:this.__data__[n]},Mn.prototype.has=function(n){return"__proto__"!=n&&Ke.call(this.__data__,n);
},Mn.prototype.set=function(n,t){return"__proto__"!=n&&(this.__data__[n]=t),this},Dn.prototype.push=function(n){var t=this.data;typeof n=="string"||ae(n)?t.set.add(n):t.hash[n]=true},ee.Cache=Mn,$n.after=function(n,t){if(typeof t!="function"){if(typeof n!="function")throw new Be(L);var r=n;n=t,t=r}return n=vu(n=+n)?n:0,function(){return 1>--n?t.apply(this,arguments):void 0}},$n.ary=function(n,t,r){return r&&jr(n,t,r)&&(t=null),t=n&&null==t?n.length:yu(+t||0,0),pr(n,R,null,null,null,null,t)},$n.assign=Wo,
$n.at=to,$n.before=te,$n.bind=vo,$n.bindAll=go,$n.bindKey=yo,$n.callback=je,$n.chain=Vr,$n.chunk=function(n,t,r){t=(r?jr(n,t,r):null==t)?1:yu(+t||1,1),r=0;for(var e=n?n.length:0,u=-1,o=Ce(He(e/t));r<e;)o[++u]=It(n,r,r+=t);return o},$n.compact=function(n){for(var t=-1,r=n?n.length:0,e=-1,u=[];++t<r;){var o=n[t];o&&(u[++e]=o)}return u},$n.constant=ke,$n.countBy=ro,$n.create=function(n,t,r){var e=Uu(n);return r&&jr(n,t,r)&&(t=null),t?Tu(e,t):e},$n.curry=mo,$n.curryRight=wo,$n.debounce=re,$n.defaults=To,
$n.defer=bo,$n.delay=xo,$n.difference=Vu,$n.drop=$r,$n.dropRight=Lr,$n.dropRightWhile=function(n,t,r){return n&&n.length?Nt(n,yr(t,r,3),true,true):[]},$n.dropWhile=function(n,t,r){return n&&n.length?Nt(n,yr(t,r,3),true):[]},$n.fill=function(n,t,r,e){var u=n?n.length:0;if(!u)return[];for(r&&typeof r!="number"&&jr(n,t,r)&&(r=0,e=u),u=n.length,r=null==r?0:+r||0,0>r&&(r=-r>u?0:u+r),e=e===w||e>u?u:+e||0,0>e&&(e+=u),u=r>e?0:e>>>0,r>>>=0;r<u;)n[r++]=t;return n},$n.filter=Gr,$n.flatten=function(n,t,r){var e=n?n.length:0;
return r&&jr(n,t,r)&&(t=false),e?st(n,t):[]},$n.flattenDeep=function(n){return n&&n.length?st(n,true):[]},$n.flow=Ao,$n.flowRight=jo,$n.forEach=oo,$n.forEachRight=io,$n.forIn=Fo,$n.forInRight=$o,$n.forOwn=Lo,$n.forOwnRight=Bo,$n.functions=ve,$n.groupBy=fo,$n.indexBy=ao,$n.initial=function(n){return Lr(n,1)},$n.intersection=function(){for(var n=[],t=-1,e=arguments.length,u=[],o=dr(),i=o==r,f=[];++t<e;){var a=arguments[t];(Io(a)||oe(a))&&(n.push(a),u.push(i&&120<=a.length?zu(t&&a):null))}if(e=n.length,2>e)return f;
var i=n[0],c=-1,l=i?i.length:0,s=u[0];n:for(;++c<l;)if(a=i[c],0>(s?Pn(s,a):o(f,a,0))){for(t=e;--t;){var p=u[t];if(0>(p?Pn(p,a):o(n[t],a,0)))continue n}s&&s.push(a),f.push(a)}return f},$n.invert=function(n,t,r){r&&jr(n,t,r)&&(t=null),r=-1;for(var e=zo(n),u=e.length,o={};++r<u;){var i=e[r],f=n[i];t?Ke.call(o,f)?o[f].push(i):o[f]=[i]:o[f]=i}return o},$n.invoke=co,$n.keys=zo,$n.keysIn=ge,$n.map=Xr,$n.mapValues=function(n,t,r){var e={};return t=yr(t,r,3),ht(n,function(n,r,u){e[r]=t(n,r,u)}),e},$n.matches=function(n){
return wt(ot(n,true))},$n.matchesProperty=function(n,t){return bt(n,ot(t,true))},$n.memoize=ee,$n.merge=Mo,$n.method=Xo,$n.methodOf=Ho,$n.mixin=Ee,$n.negate=function(n){if(typeof n!="function")throw new Be(L);return function(){return!n.apply(this,arguments)}},$n.omit=Do,$n.once=function(n){return te(2,n)},$n.pairs=function(n){for(var t=-1,r=zo(n),e=r.length,u=Ce(e);++t<e;){var o=r[t];u[t]=[o,n[o]]}return u},$n.partial=ko,$n.partialRight=Oo,$n.partition=lo,$n.pick=Po,$n.pluck=function(n,t){return Xr(n,Re(t));
},$n.property=Re,$n.propertyOf=function(n){return function(t){return gt(n,Nr(t),t+"")}},$n.pull=function(){var n=arguments,t=n[0];if(!t||!t.length)return t;for(var r=0,e=dr(),u=n.length;++r<u;)for(var o=0,i=n[r];-1<(o=e(t,i,o));)au.call(t,o,1);return t},$n.pullAt=Gu,$n.range=function(n,t,r){r&&jr(n,t,r)&&(t=r=null),n=+n||0,r=null==r?1:+r||0,null==t?(t=n,n=0):t=+t||0;var e=-1;t=yu(He((t-n)/(r||1)),0);for(var u=Ce(t);++e<t;)u[e]=n,n+=r;return u},$n.rearg=Eo,$n.reject=function(n,t,r){var e=Io(n)?Gn:ct;
return t=yr(t,r,3),e(n,function(n,r,e){return!t(n,r,e)})},$n.remove=function(n,t,r){var e=[];if(!n||!n.length)return e;var u=-1,o=[],i=n.length;for(t=yr(t,r,3);++u<i;)r=n[u],t(r,u,n)&&(e.push(r),o.push(u));return kt(n,o),e},$n.rest=Dr,$n.restParam=ue,$n.set=function(n,t,r){if(null==n)return n;var e=t+"";t=null!=n[e]||kr(t,n)?[e]:Nr(t);for(var e=-1,u=t.length,o=u-1,i=n;null!=i&&++e<u;){var f=t[e];ae(i)&&(e==o?i[f]=r:null==i[f]&&(i[f]=Ar(t[e+1])?[]:{})),i=i[f]}return n},$n.shuffle=Qr,$n.slice=function(n,t,r){
var e=n?n.length:0;return e?(r&&typeof r!="number"&&jr(n,t,r)&&(t=0,r=e),It(n,t,r)):[]},$n.sortBy=function(n,t,r){if(null==n)return[];r&&jr(n,t,r)&&(t=null);var e=-1;return t=yr(t,r,3),n=mt(n,function(n,r,u){return{a:t(n,r,u),b:++e,c:n}}),Ct(n,a)},$n.sortByAll=ho,$n.sortByOrder=function(n,t,r,e){return null==n?[]:(e&&jr(t,r,e)&&(r=null),Io(t)||(t=null==t?[]:[t]),Io(r)||(r=null==r?[]:[r]),St(n,t,r))},$n.spread=function(n){if(typeof n!="function")throw new Be(L);return function(t){return n.apply(this,t);
}},$n.take=function(n,t,r){return n&&n.length?((r?jr(n,t,r):null==t)&&(t=1),It(n,0,0>t?0:t)):[]},$n.takeRight=function(n,t,r){var e=n?n.length:0;return e?((r?jr(n,t,r):null==t)&&(t=1),t=e-(+t||0),It(n,0>t?0:t)):[]},$n.takeRightWhile=function(n,t,r){return n&&n.length?Nt(n,yr(t,r,3),false,true):[]},$n.takeWhile=function(n,t,r){return n&&n.length?Nt(n,yr(t,r,3)):[]},$n.tap=function(n,t,r){return t.call(r,n),n},$n.throttle=function(n,t,r){var e=true,u=true;if(typeof n!="function")throw new Be(L);return false===r?e=false:ae(r)&&(e="leading"in r?!!r.leading:e,
u="trailing"in r?!!r.trailing:u),Fn.leading=e,Fn.maxWait=+t,Fn.trailing=u,re(n,t,Fn)},$n.thru=Yr,$n.times=function(n,t,r){if(n=nu(n),1>n||!vu(n))return[];var e=-1,u=Ce(du(n,ku));for(t=Bt(t,r,1);++e<n;)e<ku?u[e]=t(e):t(e);return u},$n.toArray=function(n){var t=n?Pu(n):0;return Er(t)?t?qn(n):[]:ye(n)},$n.toPlainObject=_e,$n.transform=function(n,t,r,e){var u=Io(n)||he(n);return t=yr(t,e,4),null==r&&(u||ae(n)?(e=n.constructor,r=u?Io(n)?new e:[]:Uu(Co(e)&&e.prototype)):r={}),(u?Kn:ht)(n,function(n,e,u){
return t(r,n,e,u)}),r},$n.union=Hu,$n.uniq=Pr,$n.unzip=qr,$n.values=ye,$n.valuesIn=function(n){return Ut(n,ge(n))},$n.where=function(n,t){return Gr(n,wt(t))},$n.without=Qu,$n.wrap=function(n,t){return t=null==t?Oe:t,pr(t,E,null,[n],[])},$n.xor=function(){for(var n=-1,t=arguments.length;++n<t;){var r=arguments[n];if(Io(r)||oe(r))var e=e?ft(e,r).concat(ft(r,e)):r}return e?Tt(e):[]},$n.zip=no,$n.zipObject=Kr,$n.backflow=jo,$n.collect=Xr,$n.compose=jo,$n.each=oo,$n.eachRight=io,$n.extend=Wo,$n.iteratee=je,
$n.methods=ve,$n.object=Kr,$n.select=Gr,$n.tail=Dr,$n.unique=Pr,Ee($n,$n),$n.add=function(n,t){return(+n||0)+(+t||0)},$n.attempt=Jo,$n.camelCase=qo,$n.capitalize=function(n){return(n=u(n))&&n.charAt(0).toUpperCase()+n.slice(1)},$n.clone=function(n,t,r,e){return t&&typeof t!="boolean"&&jr(n,t,r)?t=false:typeof t=="function"&&(e=r,r=t,t=false),r=typeof r=="function"&&Bt(r,e,1),ot(n,t,r)},$n.cloneDeep=function(n,t,r){return t=typeof t=="function"&&Bt(t,r,1),ot(n,true,t)},$n.deburr=de,$n.endsWith=function(n,t,r){
n=u(n),t+="";var e=n.length;return r=r===w?e:du(0>r?0:+r||0,e),r-=t.length,0<=r&&n.indexOf(t,r)==r},$n.escape=function(n){return(n=u(n))&&hn.test(n)?n.replace(sn,l):n},$n.escapeRegExp=me,$n.every=Zr,$n.find=eo,$n.findIndex=Yu,$n.findKey=Uo,$n.findLast=uo,$n.findLastIndex=Zu,$n.findLastKey=No,$n.findWhere=function(n,t){return eo(n,wt(t))},$n.first=Br,$n.get=function(n,t,r){return n=null==n?w:gt(n,Nr(t),t+""),n===w?r:n},$n.has=function(n,t){if(null==n)return false;var r=Ke.call(n,t);return r||kr(t)||(t=Nr(t),
n=1==t.length?n:gt(n,It(t,0,-1)),t=Mr(t),r=null!=n&&Ke.call(n,t)),r},$n.identity=Oe,$n.includes=Jr,$n.indexOf=zr,$n.inRange=function(n,t,r){return t=+t||0,"undefined"===typeof r?(r=t,t=0):r=+r||0,n>=du(t,r)&&n<yu(t,r)},$n.isArguments=oe,$n.isArray=Io,$n.isBoolean=function(n){return true===n||false===n||h(n)&&Ye.call(n)==D},$n.isDate=function(n){return h(n)&&Ye.call(n)==P},$n.isElement=ie,$n.isEmpty=function(n){if(null==n)return true;var t=Pu(n);return Er(t)&&(Io(n)||pe(n)||oe(n)||h(n)&&Co(n.splice))?!t:!zo(n).length;
},$n.isEqual=function(n,t,r,e){return r=typeof r=="function"&&Bt(r,e,3),!r&&Ir(n)&&Ir(t)?n===t:(e=r?r(n,t):w,e===w?yt(n,t,r):!!e)},$n.isError=fe,$n.isFinite=Ro,$n.isFunction=Co,$n.isMatch=function(n,t,r,e){var u=zo(t),o=u.length;if(!o)return true;if(null==n)return false;if(r=typeof r=="function"&&Bt(r,e,3),n=Ur(n),!r&&1==o){var i=u[0];if(e=t[i],Ir(e))return e===n[i]&&(e!==w||i in n)}for(var i=Ce(o),f=Ce(o);o--;)e=i[o]=t[u[o]],f[o]=Ir(e);return dt(n,u,i,f,r)},$n.isNaN=function(n){return le(n)&&n!=+n},$n.isNative=ce,
$n.isNull=function(n){return null===n},$n.isNumber=le,$n.isObject=ae,$n.isPlainObject=So,$n.isRegExp=se,$n.isString=pe,$n.isTypedArray=he,$n.isUndefined=function(n){return n===w},$n.kebabCase=Ko,$n.last=Mr,$n.lastIndexOf=function(n,t,r){var e=n?n.length:0;if(!e)return-1;var u=e;if(typeof r=="number")u=(0>r?yu(e+r,0):du(r||0,e-1))+1;else if(r)return u=$t(n,t,true)-1,n=n[u],(t===t?t===n:n!==n)?u:-1;if(t!==t)return p(n,u,true);for(;u--;)if(n[u]===t)return u;return-1},$n.max=Qo,$n.min=ni,$n.noConflict=function(){
return _._=Ze,this},$n.noop=Ie,$n.now=_o,$n.pad=function(n,t,r){n=u(n),t=+t;var e=n.length;return e<t&&vu(t)?(e=(t-e)/2,t=nu(e),e=He(e),r=cr("",e,r),r.slice(0,t)+n+r):n},$n.padLeft=Vo,$n.padRight=Yo,$n.parseInt=we,$n.random=function(n,t,r){r&&jr(n,t,r)&&(t=r=null);var e=null==n,u=null==t;return null==r&&(u&&typeof n=="boolean"?(r=n,n=1):typeof t=="boolean"&&(r=t,u=true)),e&&u&&(t=1,u=false),n=+n||0,u?(t=n,n=0):t=+t||0,r||n%1||t%1?(r=xu(),du(n+r*(t-n+parseFloat("1e-"+((r+"").length-1))),t)):Ot(n,t)},$n.reduce=so,
$n.reduceRight=po,$n.repeat=be,$n.result=function(n,t,r){var e=null==n?w:n[t];return e===w&&(null==n||kr(t,n)||(t=Nr(t),n=1==t.length?n:gt(n,It(t,0,-1)),e=null==n?w:n[Mr(t)]),e=e===w?r:e),Co(e)?e.call(n):e},$n.runInContext=m,$n.size=function(n){var t=n?Pu(n):0;return Er(t)?t:zo(n).length},$n.snakeCase=Zo,$n.some=ne,$n.sortedIndex=Ju,$n.sortedLastIndex=Xu,$n.startCase=Go,$n.startsWith=function(n,t,r){return n=u(n),r=null==r?0:du(0>r?0:+r||0,n.length),n.lastIndexOf(t,r)==r},$n.sum=function(n,t,r){r&&jr(n,t,r)&&(t=null);
var e=yr(),u=null==t;if(e===ut&&u||(u=false,t=e(t,r,3)),u){for(n=Io(n)?n:Tr(n),t=n.length,r=0;t--;)r+=+n[t]||0;n=r}else n=Wt(n,t);return n},$n.template=function(n,t,r){var e=$n.templateSettings;r&&jr(n,t,r)&&(t=r=null),n=u(n),t=tt(Tu({},r||t),e,nt),r=tt(Tu({},t.imports),e.imports,nt);var o,i,f=zo(r),a=Ut(r,f),c=0;r=t.interpolate||Rn;var l="__p+='";r=$e((t.escape||Rn).source+"|"+r.source+"|"+(r===gn?jn:Rn).source+"|"+(t.evaluate||Rn).source+"|$","g");var p="sourceURL"in t?"//# sourceURL="+t.sourceURL+"\n":"";
if(n.replace(r,function(t,r,e,u,f,a){return e||(e=u),l+=n.slice(c,a).replace(Cn,s),r&&(o=true,l+="'+__e("+r+")+'"),f&&(i=true,l+="';"+f+";\n__p+='"),e&&(l+="'+((__t=("+e+"))==null?'':__t)+'"),c=a+t.length,t}),l+="';",(t=t.variable)||(l="with(obj){"+l+"}"),l=(i?l.replace(fn,""):l).replace(an,"$1").replace(cn,"$1;"),l="function("+(t||"obj")+"){"+(t?"":"obj||(obj={});")+"var __t,__p=''"+(o?",__e=_.escape":"")+(i?",__j=Array.prototype.join;function print(){__p+=__j.call(arguments,'')}":";")+l+"return __p}",
t=Jo(function(){return Te(f,p+"return "+l).apply(w,a)}),t.source=l,fe(t))throw t;return t},$n.trim=xe,$n.trimLeft=function(n,t,r){var e=n;return(n=u(n))?n.slice((r?jr(e,t,r):null==t)?g(n):i(n,t+"")):n},$n.trimRight=function(n,t,r){var e=n;return(n=u(n))?(r?jr(e,t,r):null==t)?n.slice(0,y(n)+1):n.slice(0,f(n,t+"")+1):n},$n.trunc=function(n,t,r){r&&jr(n,t,r)&&(t=null);var e=S;if(r=W,null!=t)if(ae(t)){var o="separator"in t?t.separator:o,e="length"in t?+t.length||0:e;r="omission"in t?u(t.omission):r}else e=+t||0;
if(n=u(n),e>=n.length)return n;if(e-=r.length,1>e)return r;if(t=n.slice(0,e),null==o)return t+r;if(se(o)){if(n.slice(e).search(o)){var i,f=n.slice(0,e);for(o.global||(o=$e(o.source,(kn.exec(o)||"")+"g")),o.lastIndex=0;n=o.exec(f);)i=n.index;t=t.slice(0,null==i?e:i)}}else n.indexOf(o,e)!=e&&(o=t.lastIndexOf(o),-1<o&&(t=t.slice(0,o)));return t+r},$n.unescape=function(n){return(n=u(n))&&pn.test(n)?n.replace(ln,d):n},$n.uniqueId=function(n){var t=++Ve;return u(n)+t},$n.words=Ae,$n.all=Zr,$n.any=ne,$n.contains=Jr,
$n.detect=eo,$n.foldl=so,$n.foldr=po,$n.head=Br,$n.include=Jr,$n.inject=so,Ee($n,function(){var n={};return ht($n,function(t,r){$n.prototype[r]||(n[r]=t)}),n}(),false),$n.sample=Hr,$n.prototype.sample=function(n){return this.__chain__||null!=n?this.thru(function(t){return Hr(t,n)}):Hr(this.value())},$n.VERSION=b,Kn("bind bindKey curry curryRight partial partialRight".split(" "),function(n){$n[n].placeholder=$n}),Kn(["dropWhile","filter","map","takeWhile"],function(n,t){var r=t!=$,e=t==N;zn.prototype[n]=function(n,u){
var o=this.__filtered__,i=o&&e?new zn(this):this.clone();return(i.__iteratees__||(i.__iteratees__=[])).push({done:false,count:0,index:0,iteratee:yr(n,u,1),limit:-1,type:t}),i.__filtered__=o||r,i}}),Kn(["drop","take"],function(n,t){var r=n+"While";zn.prototype[n]=function(r){var e=this.__filtered__,u=e&&!t?this.dropWhile():this.clone();return r=null==r?1:yu(nu(r)||0,0),e?t?u.__takeCount__=du(u.__takeCount__,r):Mr(u.__iteratees__).limit=r:(u.__views__||(u.__views__=[])).push({size:r,type:n+(0>u.__dir__?"Right":"")
}),u},zn.prototype[n+"Right"]=function(t){return this.reverse()[n](t).reverse()},zn.prototype[n+"RightWhile"]=function(n,t){return this.reverse()[r](n,t).reverse()}}),Kn(["first","last"],function(n,t){var r="take"+(t?"Right":"");zn.prototype[n]=function(){return this[r](1).value()[0]}}),Kn(["initial","rest"],function(n,t){var r="drop"+(t?"":"Right");zn.prototype[n]=function(){return this[r](1)}}),Kn(["pluck","where"],function(n,t){var r=t?"filter":"map",e=t?wt:Re;zn.prototype[n]=function(n){return this[r](e(n));
}}),zn.prototype.compact=function(){return this.filter(Oe)},zn.prototype.reject=function(n,t){return n=yr(n,t,1),this.filter(function(t){return!n(t)})},zn.prototype.slice=function(n,t){n=null==n?0:+n||0;var r=0>n?this.takeRight(-n):this.drop(n);return t!==w&&(t=+t||0,r=0>t?r.dropRight(-t):r.take(t-n)),r},zn.prototype.toArray=function(){return this.drop(0)},ht(zn.prototype,function(n,t){var r=$n[t];if(r){var e=/^(?:filter|map|reject)|While$/.test(t),u=/^(?:first|last)$/.test(t);$n.prototype[t]=function(){
function t(n){return n=[n],eu.apply(n,o),r.apply($n,n)}var o=arguments,i=this.__chain__,f=this.__wrapped__,a=!!this.__actions__.length,c=f instanceof zn,l=o[0],s=c||Io(f);return s&&e&&typeof l=="function"&&1!=l.length&&(c=s=false),c=c&&!a,u&&!i?c?n.call(f):r.call($n,this.value()):s?(f=n.apply(c?f:new zn(this),o),u||!a&&!f.__actions__||(f.__actions__||(f.__actions__=[])).push({func:Yr,args:[t],thisArg:$n}),new Bn(f,i)):this.thru(t)}}}),Kn("concat join pop push replace shift sort splice split unshift".split(" "),function(n){
var t=(/^(?:replace|split)$/.test(n)?De:ze)[n],r=/^(?:push|sort|unshift)$/.test(n)?"tap":"thru",e=/^(?:join|pop|replace|shift)$/.test(n);$n.prototype[n]=function(){var n=arguments;return e&&!this.__chain__?t.apply(this.value(),n):this[r](function(r){return t.apply(r,n)})}}),ht(zn.prototype,function(n,t){var r=$n[t];if(r){var e=r.name;(Su[e]||(Su[e]=[])).push({name:t,func:r})}}),Su[ar(null,A).name]=[{name:"wrapper",func:null}],zn.prototype.clone=function(){var n=this.__actions__,t=this.__iteratees__,r=this.__views__,e=new zn(this.__wrapped__);
return e.__actions__=n?qn(n):null,e.__dir__=this.__dir__,e.__filtered__=this.__filtered__,e.__iteratees__=t?qn(t):null,e.__takeCount__=this.__takeCount__,e.__views__=r?qn(r):null,e},zn.prototype.reverse=function(){if(this.__filtered__){var n=new zn(this);n.__dir__=-1,n.__filtered__=true}else n=this.clone(),n.__dir__*=-1;return n},zn.prototype.value=function(){var n=this.__wrapped__.value();if(!Io(n))return Ft(n,this.__actions__);var t,r=this.__dir__,e=0>r;t=n.length;for(var u=this.__views__,o=0,i=-1,f=u?u.length:0;++i<f;){
var a=u[i],c=a.size;switch(a.type){case"drop":o+=c;break;case"dropRight":t-=c;break;case"take":t=du(t,o+c);break;case"takeRight":o=yu(o,t-c)}}t={start:o,end:t},u=t.start,o=t.end,t=o-u,u=e?o:u-1,o=du(t,this.__takeCount__),f=(i=this.__iteratees__)?i.length:0,a=0,c=[];n:for(;t--&&a<o;){for(var u=u+r,l=-1,s=n[u];++l<f;){var p=i[l],h=p.iteratee,_=p.type;if(_==N){if(p.done&&(e?u>p.index:u<p.index)&&(p.count=0,p.done=false),p.index=u,!(p.done||(_=p.limit,p.done=-1<_?p.count++>=_:!h(s))))continue n}else if(p=h(s),
_==$)s=p;else if(!p){if(_==F)continue n;break n}}c[a++]=s}return c},$n.prototype.chain=function(){return Vr(this)},$n.prototype.commit=function(){return new Bn(this.value(),this.__chain__)},$n.prototype.plant=function(n){for(var t,r=this;r instanceof Ln;){var e=Fr(r);t?u.__wrapped__=e:t=e;var u=e,r=r.__wrapped__}return u.__wrapped__=n,t},$n.prototype.reverse=function(){var n=this.__wrapped__;return n instanceof zn?(this.__actions__.length&&(n=new zn(this)),new Bn(n.reverse(),this.__chain__)):this.thru(function(n){
return n.reverse()})},$n.prototype.toString=function(){return this.value()+""},$n.prototype.run=$n.prototype.toJSON=$n.prototype.valueOf=$n.prototype.value=function(){return Ft(this.__wrapped__,this.__actions__)},$n.prototype.collect=$n.prototype.map,$n.prototype.head=$n.prototype.first,$n.prototype.select=$n.prototype.filter,$n.prototype.tail=$n.prototype.rest,$n}var w,b="3.7.0",x=1,A=2,j=4,k=8,O=16,E=32,I=64,R=128,C=256,S=30,W="...",T=150,U=16,N=0,F=1,$=2,L="Expected a function",B="__lodash_placeholder__",z="[object Arguments]",M="[object Array]",D="[object Boolean]",P="[object Date]",q="[object Error]",K="[object Function]",V="[object Number]",Y="[object Object]",Z="[object RegExp]",G="[object String]",J="[object ArrayBuffer]",X="[object Float32Array]",H="[object Float64Array]",Q="[object Int8Array]",nn="[object Int16Array]",tn="[object Int32Array]",rn="[object Uint8Array]",en="[object Uint8ClampedArray]",un="[object Uint16Array]",on="[object Uint32Array]",fn=/\b__p\+='';/g,an=/\b(__p\+=)''\+/g,cn=/(__e\(.*?\)|\b__t\))\+'';/g,ln=/&(?:amp|lt|gt|quot|#39|#96);/g,sn=/[&<>"'`]/g,pn=RegExp(ln.source),hn=RegExp(sn.source),_n=/<%-([\s\S]+?)%>/g,vn=/<%([\s\S]+?)%>/g,gn=/<%=([\s\S]+?)%>/g,yn=/\.|\[(?:[^[\]]+|(["'])(?:(?!\1)[^\n\\]|\\.)*?)\1\]/,dn=/^\w*$/,mn=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g,wn=/[.*+?^${}()|[\]\/\\]/g,bn=RegExp(wn.source),xn=/[\u0300-\u036f\ufe20-\ufe23]/g,An=/\\(\\)?/g,jn=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,kn=/\w*$/,On=/^0[xX]/,En=/^\[object .+?Constructor\]$/,In=/[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g,Rn=/($^)/,Cn=/['\n\r\u2028\u2029\\]/g,Sn=RegExp("[A-Z\\xc0-\\xd6\\xd8-\\xde]+(?=[A-Z\\xc0-\\xd6\\xd8-\\xde][a-z\\xdf-\\xf6\\xf8-\\xff]+)|[A-Z\\xc0-\\xd6\\xd8-\\xde]?[a-z\\xdf-\\xf6\\xf8-\\xff]+|[A-Z\\xc0-\\xd6\\xd8-\\xde]+|[0-9]+","g"),Wn=" \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000",Tn="Array ArrayBuffer Date Error Float32Array Float64Array Function Int8Array Int16Array Int32Array Math Number Object RegExp Set String _ clearTimeout document isFinite parseInt setTimeout TypeError Uint8Array Uint8ClampedArray Uint16Array Uint32Array WeakMap window".split(" "),Un={};
Un[X]=Un[H]=Un[Q]=Un[nn]=Un[tn]=Un[rn]=Un[en]=Un[un]=Un[on]=true,Un[z]=Un[M]=Un[J]=Un[D]=Un[P]=Un[q]=Un[K]=Un["[object Map]"]=Un[V]=Un[Y]=Un[Z]=Un["[object Set]"]=Un[G]=Un["[object WeakMap]"]=false;var Nn={};Nn[z]=Nn[M]=Nn[J]=Nn[D]=Nn[P]=Nn[X]=Nn[H]=Nn[Q]=Nn[nn]=Nn[tn]=Nn[V]=Nn[Y]=Nn[Z]=Nn[G]=Nn[rn]=Nn[en]=Nn[un]=Nn[on]=true,Nn[q]=Nn[K]=Nn["[object Map]"]=Nn["[object Set]"]=Nn["[object WeakMap]"]=false;var Fn={leading:false,maxWait:0,trailing:false},$n={"\xc0":"A","\xc1":"A","\xc2":"A","\xc3":"A","\xc4":"A","\xc5":"A",
"\xe0":"a","\xe1":"a","\xe2":"a","\xe3":"a","\xe4":"a","\xe5":"a","\xc7":"C","\xe7":"c","\xd0":"D","\xf0":"d","\xc8":"E","\xc9":"E","\xca":"E","\xcb":"E","\xe8":"e","\xe9":"e","\xea":"e","\xeb":"e","\xcc":"I","\xcd":"I","\xce":"I","\xcf":"I","\xec":"i","\xed":"i","\xee":"i","\xef":"i","\xd1":"N","\xf1":"n","\xd2":"O","\xd3":"O","\xd4":"O","\xd5":"O","\xd6":"O","\xd8":"O","\xf2":"o","\xf3":"o","\xf4":"o","\xf5":"o","\xf6":"o","\xf8":"o","\xd9":"U","\xda":"U","\xdb":"U","\xdc":"U","\xf9":"u","\xfa":"u",
"\xfb":"u","\xfc":"u","\xdd":"Y","\xfd":"y","\xff":"y","\xc6":"Ae","\xe6":"ae","\xde":"Th","\xfe":"th","\xdf":"ss"},Ln={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","`":"&#96;"},Bn={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'","&#96;":"`"},zn={"function":true,object:true},Mn={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},Dn=zn[typeof exports]&&exports&&!exports.nodeType&&exports,Pn=zn[typeof module]&&module&&!module.nodeType&&module,qn=zn[typeof self]&&self&&self.Object&&self,Kn=zn[typeof window]&&window&&window.Object&&window,Vn=Pn&&Pn.exports===Dn&&Dn,Yn=Dn&&Pn&&typeof global=="object"&&global&&global.Object&&global||Kn!==(this&&this.window)&&Kn||qn||this,Zn=m();
typeof define=="function"&&typeof define.amd=="object"&&define.amd?(Yn._=Zn, define(function(){return Zn})):Dn&&Pn?Vn?(Pn.exports=Zn)._=Zn:Dn._=Zn:Yn._=Zn}).call(this);

File diff suppressed because it is too large Load Diff

View File

@@ -1,33 +1,20 @@
{
"name": "lodash",
"version": "3.7.0",
"main": "lodash.src.js",
"private": true,
"devDependencies": {
"curl-amd": "0.8.12",
"dojo": "~1.10.0",
"jquery": "~1.11.0",
"platform": "~1.3.0",
"qunit-extras": "~1.4.0",
"qunitjs": "~1.17.0",
"requirejs": "~2.1.0"
},
"volo": {
"type": "directory",
"ignore": [
".*",
"*.custom.*",
"*.log",
"*.map",
"*.md",
"lodash.src.js",
"bower.json",
"component.json",
"doc",
"node_modules",
"perf",
"test",
"vendor"
]
"version": "1.0.2",
"description": "A utility library delivering consistency, customization, performance, and extras.",
"homepage": "https://lodash.com/",
"license": "MIT",
"main": "./dist/lodash.js",
"keywords": ["browser", "client", "functional", "performance", "server", "speed", "util"],
"author": "John-David Dalton <john.david.dalton@gmail.com> (http://allyoucanleet.com/)",
"contributors": [
"John-David Dalton <john.david.dalton@gmail.com> (http://allyoucanleet.com/)",
"Blaine Bublitz <blaine@iceddev.com> (http://www.iceddev.com/)",
"Kit Cambridge <github@kitcambridge.be> (http://kitcambridge.be/)",
"Mathias Bynens <mathias@qiwi.be> (https://mathiasbynens.be/)"
],
"repository": "lodash/lodash",
"jam": {
"main": "./dist/lodash.compat.js"
}
}

View File

@@ -1,149 +0,0 @@
;(function(window) {
'use strict';
/** The base path of the lodash builds. */
var basePath = '../';
/** The lodash build to load. */
var build = (build = /build=([^&]+)/.exec(location.search)) && decodeURIComponent(build[1]);
/** The other library to load. */
var other = (other = /other=([^&]+)/.exec(location.search)) && decodeURIComponent(other[1]);
/** The `ui` object. */
var ui = {};
/*--------------------------------------------------------------------------*/
/**
* Registers an event listener on an element.
*
* @private
* @param {Element} element The element.
* @param {string} eventName The name of the event.
* @param {Function} handler The event handler.
* @returns {Element} The element.
*/
function addListener(element, eventName, handler) {
if (typeof element.addEventListener != 'undefined') {
element.addEventListener(eventName, handler, false);
} else if (typeof element.attachEvent != 'undefined') {
element.attachEvent('on' + eventName, handler);
}
}
/*--------------------------------------------------------------------------*/
// Initialize controls.
addListener(window, 'load', function() {
function eventHandler(event) {
var buildIndex = buildList.selectedIndex,
otherIndex = otherList.selectedIndex,
search = location.search.replace(/^\?|&?(?:build|other)=[^&]*&?/g, '');
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
location.href =
location.href.split('?')[0] + '?' +
(search ? search + '&' : '') +
'build=' + (buildIndex < 0 ? build : buildList[buildIndex].value) + '&' +
'other=' + (otherIndex < 0 ? other : otherList[otherIndex].value);
}
var span1 = document.createElement('span');
span1.style.cssText = 'float:right';
span1.innerHTML =
'<label for="perf-build">Build: </label>' +
'<select id="perf-build">' +
'<option value="lodash-compat">lodash (compat)</option>' +
'<option value="lodash-modern">lodash (modern)</option>' +
'<option value="lodash-custom-dev">lodash (custom development)</option>' +
'<option value="lodash-custom">lodash (custom production)</option>' +
'</select>';
var span2 = document.createElement('span');
span2.style.cssText = 'float:right';
span2.innerHTML =
'<label for="perf-other">Other Library: </label>' +
'<select id="perf-other">' +
'<option value="underscore-dev">Underscore (development)</option>' +
'<option value="underscore">Underscore (production)</option>' +
'<option value="lodash-compat">lodash (compat)</option>' +
'<option value="lodash-modern">lodash (modern)</option>' +
'<option value="lodash-custom-dev">lodash (custom development)</option>' +
'<option value="lodash-custom">lodash (custom production)</option>' +
'</select>';
var buildList = span1.lastChild,
otherList = span2.lastChild,
toolbar = document.getElementById('perf-toolbar');
toolbar.appendChild(span2);
toolbar.appendChild(span1);
buildList.selectedIndex = (function() {
switch (build) {
case 'lodash-compat': return 0;
case 'lodash-custom-dev': return 2;
case 'lodash-custom': return 3;
case 'lodash-modern':
case null: return 1;
}
return -1;
}());
otherList.selectedIndex = (function() {
switch (other) {
case 'underscore-dev': return 0;
case 'lodash-compat': return 2;
case 'lodash-modern': return 3;
case 'lodash-custom-dev': return 4;
case 'lodash-custom': return 5;
case 'underscore':
case null: return 1;
}
return -1;
}());
addListener(buildList, 'change', eventHandler);
addListener(otherList, 'change', eventHandler);
});
// The lodash build file path.
ui.buildPath = (function() {
var result;
switch (build) {
case 'lodash-compat': result = 'lodash.compat.min.js'; break;
case 'lodash-custom-dev': result = 'lodash.custom.js'; break;
case 'lodash-custom': result = 'lodash.custom.min.js'; break;
case null: build = 'lodash-modern';
case 'lodash-modern': result = 'lodash.min.js'; break;
default: return build;
}
return basePath + result;
}());
// The other library file path.
ui.otherPath = (function() {
var result;
switch (other) {
case 'lodash-compat': result = 'lodash.compat.min.js'; break;
case 'lodash-modern': result = 'lodash.min.js'; break;
case 'lodash-custom-dev': result = 'lodash.custom.js'; break;
case 'lodash-custom': result = 'lodash.custom.min.js'; break;
case 'underscore-dev': result = 'vendor/underscore/underscore.js'; break;
case null: other = 'underscore';
case 'underscore': result = 'vendor/underscore/underscore-min.js'; break;
default: return other;
}
return basePath + result;
}());
ui.urlParams = { 'build': build, 'other': other };
window.ui = ui;
}(this));

View File

@@ -2,7 +2,7 @@
<html lang="en">
<head>
<meta charset="utf-8">
<title>lodash Performance Suite</title>
<title>Lo-Dash Performance Suite</title>
<style>
html, body {
margin: 0;
@@ -28,19 +28,18 @@
</head>
<body>
<div id="perf-toolbar"></div>
<script src="../node_modules/platform/platform.js"></script>
<script src="../lodash.src.js"></script>
<script src="../vendor/platform.js/platform.js"></script>
<script src="../vendor/benchmark.js/benchmark.js"></script>
<script src="../vendor/firebug-lite/src/firebug-lite-debug.js"></script>
<script src="./asset/perf-ui.js"></script>
<script src="perf-ui.js"></script>
<script>
document.write('<script src="' + ui.buildPath + '"><\/script>');
document.write('<script src="../' + ui.buildPath + '"><\/script>');
</script>
<script>
var lodash = _.noConflict();
</script>
<script>
document.write('<script src="' + ui.otherPath + '"><\/script>');
document.write('<script src="../' + ui.otherPath + '"><\/script>');
</script>
<script src="perf.js"></script>
<script>
@@ -69,8 +68,8 @@
// is the applet permitted?
if (!/[?&]nojava=true(?:&|$)/.test(location.search)) {
// is the applet really needed?
while (!(measured = new Date - begin)) {}
if (measured > 1 && !((perfNow = window.performance) && typeof (perfNow.now || perfNow.webkitNow) == 'function')) {
while (!(measured = new Date - begin)) { }
if (measured != 1 && !((perfNow = window.performance) && typeof (perfNow.now || perfNow.webkitNow) == 'function')) {
// load applet
document.write('<applet code="nano" archive="../vendor/benchmark.js/nano.jar"></applet>');
}

136
perf/perf-ui.js Normal file
View File

@@ -0,0 +1,136 @@
;(function(window) {
'use strict';
/** The Lo-Dash build to load */
var build = (/build=([^&]+)/.exec(location.search) || [])[1];
/** The other library to load */
var other = (/other=([^&]+)/.exec(location.search) || [])[1];
/** The `ui` object */
var ui = {};
/*--------------------------------------------------------------------------*/
/**
* Registers an event listener on an element.
*
* @private
* @param {Element} element The element.
* @param {String} eventName The name of the event.
* @param {Function} handler The event handler.
* @returns {Element} The element.
*/
function addListener(element, eventName, handler) {
if (typeof element.addEventListener != 'undefined') {
element.addEventListener(eventName, handler, false);
} else if (typeof element.attachEvent != 'undefined') {
element.attachEvent('on' + eventName, handler);
}
}
/*--------------------------------------------------------------------------*/
// expose Lo-Dash build file path
ui.buildPath = (function() {
switch (build) {
case 'lodash-dev': return 'dist/lodash.compat.js';
case 'lodash-modern': return 'dist/lodash.min.js';
case 'lodash-underscore': return 'dist/lodash.underscore.min.js';
case 'lodash-custom': return 'lodash.custom.min.js';
}
return 'dist/lodash.compat.min.js';
}());
// expose other library file path
ui.otherPath = (function() {
switch (other) {
case 'lodash-dev': return 'dist/lodash.compat.js';
case 'lodash-prod': return 'dist/lodash.compat.min.js';
case 'lodash-modern': return 'dist/lodash.min.js';
case 'lodash-underscore': return 'dist/lodash.underscore.min.js';
case 'lodash-custom': return 'lodash.custom.min.js';
case 'underscore-dev': return 'vendor/underscore/underscore.js';
}
return 'vendor/underscore/underscore-min.js';
}());
// initialize controls
addListener(window, 'load', function() {
function eventHandler(event) {
var search = location.search.replace(/^\?|&?(?:build|other)=[^&]*&?/g, '');
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
location.href =
location.href.split('?')[0] + '?' +
(search ? search + '&' : '') +
'build=' + buildList[buildList.selectedIndex].value + '&' +
'other=' + otherList[otherList.selectedIndex].value;
}
var span1 = document.createElement('span');
span1.style.cssText = 'float:right';
span1.innerHTML =
'<label for="perf-build">Build: </label>' +
'<select id="perf-build">' +
'<option value="lodash-dev">Lo-Dash</option>' +
'<option value="lodash-prod">Lo-Dash (minified)</option>' +
'<option value="lodash-modern">Lo-Dash (modern)</option>' +
'<option value="lodash-underscore">Lo-Dash (underscore)</option>' +
'<option value="lodash-custom">Lo-Dash (custom)</option>' +
'</select>';
var span2 = document.createElement('span');
span2.style.cssText = 'float:right';
span2.innerHTML =
'<label for="perf-other">Other Library: </label>' +
'<select id="perf-other">' +
'<option value="underscore-dev">Underscore</option>' +
'<option value="underscore-prod">Underscore (minified)</option>' +
'<option value="lodash-dev">Lo-Dash</option>' +
'<option value="lodash-prod">Lo-Dash (minified)</option>' +
'<option value="lodash-modern">Lo-Dash (modern)</option>' +
'<option value="lodash-underscore">Lo-Dash (underscore)</option>' +
'<option value="lodash-custom">Lo-Dash (custom)</option>' +
'</select>';
var buildList = span1.lastChild,
otherList = span2.lastChild,
toolbar = document.getElementById('perf-toolbar');
toolbar.appendChild(span2);
toolbar.appendChild(span1);
buildList.selectedIndex = (function() {
switch (build) {
case 'lodash-dev': return 0;
case 'lodash-modern': return 2;
case 'lodash-underscore': return 3;
case 'lodash-custom': return 4;
}
return 1;
}());
otherList.selectedIndex = (function() {
switch (other) {
case 'underscore-dev': return 0;
case 'lodash-dev': return 2;
case 'lodash-prod': return 3;
case 'lodash-modern': return 4;
case 'lodash-underscore': return 5;
case 'lodash-custom': return 6;
}
return 1;
}());
addListener(buildList, 'change', eventHandler);
addListener(otherList, 'change', eventHandler);
});
// expose `ui`
window.ui = ui;
}(this));

File diff suppressed because it is too large Load Diff

View File

@@ -1,12 +1,12 @@
cd "$(dirname "$0")"
echo "Running performance suite in node..."
node perf.js ../lodash.js && node perf.js ../lodash.min.js
node perf.js ../dist/lodash.js && node perf.js ../dist/lodash.min.js
for cmd in rhino "rhino -require" narwhal ringo phantomjs; do
for cmd in rhino narwhal ringo phantomjs; do
echo ""
echo "Running performance suite in $cmd..."
$cmd perf.js ../lodash.src.js
$cmd perf.js ../dist/lodash.compat.js && $cmd perf.js ../dist/lodash.compat.min.js
done
echo ""

View File

@@ -1,157 +0,0 @@
;(function() {
/** Used to determine if values are of the language type Object. */
var objectTypes = {
'function': true,
'object': true
};
/** Used as the `Set#toString` return value. */
var nativeString = String(Object.prototype.toString).replace(/toString/g, 'Set');
/** Detect free variable `exports`. */
var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = objectTypes[typeof module] && module && !module.nodeType && module;
/** Detect free variable `global` from Node.js. */
var freeGlobal = freeExports && freeModule && typeof global == 'object' && global;
/** Detect free variable `self`. */
var freeSelf = objectTypes[typeof self] && self && self.Object && self;
/** Detect free variable `window`. */
var freeWindow = objectTypes[typeof window] && window && window.Object && window;
/**
* Used as a reference to the global object.
*
* The `this` value is used if it is the global object to avoid Greasemonkey's
* restricted `window` object, otherwise the `window` object is used.
*/
var root = freeGlobal || ((freeWindow !== (this && this.window)) && freeWindow) || freeSelf || this;
/*--------------------------------------------------------------------------*/
/**
* Installs `Set` on the given `context` object.
*
* @memberOf exports
* @param {Object} context The context object.
*/
function runInContext(context) {
/**
* Creates a `Set` object.
*/
function Set() {
this.__cache__ = {};
}
/**
* Gets the index at which the first occurrence of `value` is found using
* strict equality for comparisons, i.e. `===`.
*
* @private
* @param {Array} array The array to search.
* @param {*} value The value to search for.
* @returns {number} Returns the index of the matched value or `-1`.
*/
function indexOf(array, value) {
var index = -1,
length = array.length;
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
}
/**
* Checks if `value` is in the set.
*
* @memberOf Set
* @param {*} value The value to search for.
* @returns {boolean} Returns `true` if `value` is found, else `false`.
*/
function has(value) {
var type = typeof value,
cache = this.__cache__;
if (type == 'boolean' || value == null) {
return cache[value] || false;
}
if (type != 'number' && type != 'string') {
type = 'object';
}
var key = type == 'number' ? value : '_' + value;
cache = (cache = cache[type]) && cache[key];
return type == 'object'
? (cache && indexOf(cache, value) > -1 ? true : false)
: (cache || false);
}
/**
* Adds `value` to the set.
*
* @memberOf Set
* @param {*} value The value to add.
*/
function add(value) {
var cache = this.__cache__,
type = typeof value;
if (type == 'boolean' || value == null) {
cache[value] = true;
} else {
if (type != 'number' && type != 'string') {
type = 'object';
}
var key = type == 'number' ? value : '_' + value,
typeCache = cache[type] || (cache[type] = {});
if (type == 'object') {
var array = typeCache[key];
if (array) {
array.push(value);
} else {
typeCache[key] = [value];
}
} else {
typeCache[key] = true;
}
}
}
/**
* Produces the `toString` result of `Set`.
*
* @static
* @memberOf Set
* @returns {string} Returns the string result.
*/
function toString() {
return nativeString;
}
Set.toString = toString;
Set.prototype.add = add;
Set.prototype.has = has;
if (!root.Set) {
context.Set = Set;
}
}
/*--------------------------------------------------------------------------*/
if (freeExports) {
freeExports.runInContext = runInContext;
} else {
runInContext(root);
}
}.call(this));

View File

@@ -1,173 +0,0 @@
;(function(window) {
'use strict';
/** The base path of the lodash builds. */
var basePath = '../';
/** The lodash build to load. */
var build = (build = /build=([^&]+)/.exec(location.search)) && decodeURIComponent(build[1]);
/** The module loader to use. */
var loader = (loader = /loader=([^&]+)/.exec(location.search)) && decodeURIComponent(loader[1]);
/** The `ui` object. */
var ui = {};
/*--------------------------------------------------------------------------*/
/**
* Registers an event listener on an element.
*
* @private
* @param {Element} element The element.
* @param {string} eventName The name of the event.
* @param {Function} handler The event handler.
* @returns {Element} The element.
*/
function addListener(element, eventName, handler) {
if (typeof element.addEventListener != 'undefined') {
element.addEventListener(eventName, handler, false);
} else if (typeof element.attachEvent != 'undefined') {
element.attachEvent('on' + eventName, handler);
}
}
/*--------------------------------------------------------------------------*/
// Initialize controls.
addListener(window, 'load', function() {
function eventHandler(event) {
var buildIndex = buildList.selectedIndex,
loaderIndex = loaderList.selectedIndex,
search = location.search.replace(/^\?|&?(?:build|loader)=[^&]*&?/g, '');
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
location.href =
location.href.split('?')[0] + '?' +
(search ? search + '&' : '') +
'build=' + (buildIndex < 0 ? build : buildList[buildIndex].value) + '&' +
'loader=' + (loaderIndex < 0 ? loader : loaderList[loaderIndex].value);
}
function init() {
var toolbar = document.getElementById('qunit-testrunner-toolbar');
if (!toolbar) {
setTimeout(init, 15);
return;
}
toolbar.appendChild(span1);
toolbar.appendChild(span2);
buildList.selectedIndex = (function() {
switch (build) {
case 'lodash-compat': return 1;
case 'lodash-modern-dev': return 2;
case 'lodash-modern': return 3;
case 'lodash-custom-dev': return 4;
case 'lodash-custom': return 5;
case 'lodash-compat-dev':
case null: return 0;
}
return -1;
}());
loaderList.selectedIndex = (function() {
switch (loader) {
case 'curl': return 1;
case 'dojo': return 2;
case 'requirejs': return 3;
case 'none':
case null: return 0;
}
return -1;
}());
addListener(buildList, 'change', eventHandler);
addListener(loaderList, 'change', eventHandler);
}
var span1 = document.createElement('span');
span1.style.cssText = 'float:right';
span1.innerHTML =
'<label for="qunit-build">Build: </label>' +
'<select id="qunit-build">' +
'<option value="lodash-compat-dev">lodash (compat development)</option>' +
'<option value="lodash-compat">lodash (compat production)</option>' +
'<option value="lodash-modern-dev">lodash (modern development)</option>' +
'<option value="lodash-modern">lodash (modern production)</option>' +
'<option value="lodash-custom-dev">lodash (custom development)</option>' +
'<option value="lodash-custom">lodash (custom production)</option>' +
'</select>';
var span2 = document.createElement('span');
span2.style.cssText = 'float:right';
span2.innerHTML =
'<label for="qunit-loader">Loader: </label>' +
'<select id="qunit-loader">' +
'<option value="none">None</option>' +
'<option value="curl">Curl</option>' +
'<option value="dojo">Dojo</option>' +
'<option value="requirejs">RequireJS</option>' +
'</select>';
var buildList = span1.lastChild,
loaderList = span2.lastChild;
setTimeout(function() {
ui.timing.loadEventEnd = +new Date;
}, 1);
init();
});
// Used to indicate testing a foreign file.
ui.isForeign = RegExp('^(\\w+:)?//').test(build);
// Used to indicate testing a modularized build.
ui.isModularize = /\b(?:amd|commonjs|es6?|node|npm|(index|main)\.js)\b/.test([location.pathname, location.search]);
// Used to indicate testing in Sauce Labs' automated test cloud.
ui.isSauceLabs = location.port == '9001';
// Used to indicate that lodash is in strict mode.
ui.isStrict = /\bes6?\b/.test([location.pathname, location.search]);
// The lodash build file path.
ui.buildPath = (function() {
var result;
switch (build) {
case 'lodash-compat': result = 'lodash.compat.min.js'; break;
case 'lodash-modern-dev': result = 'lodash.js'; break;
case 'lodash-modern': result = 'lodash.min.js'; break;
case 'lodash-custom-dev': result = 'lodash.custom.js'; break;
case 'lodash-custom': result = 'lodash.custom.min.js'; break;
case null: build = 'lodash-compat-dev';
case 'lodash-compat-dev': result = 'lodash.src.js'; break;
default: return build;
}
return basePath + result;
}());
// The module loader file path.
ui.loaderPath = (function() {
var result;
switch (loader) {
case 'curl': result = 'node_modules/curl-amd/dist/curl-kitchen-sink/curl.js'; break;
case 'dojo': result = 'node_modules/dojo/dojo.js'; break;
case 'requirejs': result = 'node_modules/requirejs/require.js'; break;
case null: loader = 'none'; return '';
default: return loader;
}
return basePath + result;
}());
ui.urlParams = { 'build': build, 'loader': loader };
ui.timing = { 'loadEventEnd': 0 };
window.ui = ui;
}(this));

View File

@@ -1,102 +0,0 @@
;(function() {
/** Used to determine if values are of the language type Object. */
var objectTypes = {
'function': true,
'object': true
};
/** Used as the `WeakMap#toString` return value. */
var nativeString = String(Object.prototype.toString).replace(/toString/g, 'WeakMap');
/** Detect free variable `exports`. */
var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = objectTypes[typeof module] && module && !module.nodeType && module;
/** Detect free variable `global` from Node.js. */
var freeGlobal = freeExports && freeModule && typeof global == 'object' && global;
/** Detect free variable `self`. */
var freeSelf = objectTypes[typeof self] && self && self.Object && self;
/** Detect free variable `window`. */
var freeWindow = objectTypes[typeof window] && window && window.Object && window;
/**
* Used as a reference to the global object.
*
* The `this` value is used if it is the global object to avoid Greasemonkey's
* restricted `window` object, otherwise the `window` object is used.
*/
var root = freeGlobal || ((freeWindow !== (this && this.window)) && freeWindow) || freeSelf || this;
/*--------------------------------------------------------------------------*/
/**
* Installs `WeakMap` on the given `context` object.
*
* @memberOf exports
* @param {Object} context The context object.
*/
function runInContext(context) {
/**
* Creates a `WeakMap` object.
*/
function WeakMap() {
// No operation performed.
}
/**
* Gets the value associated with the given key.
*
* @memberOf WeakMap
* @param {Object} key The key object.
* @returns {*} Returns the associated value, else `undefined`.
*/
function get(key) {
return key.__weakmap__;
}
/**
* Sets a value for the given key.
*
* @memberOf WeakMap
* @param {Object} key The key object.
* @param {*} value The value to set.
*/
function set(key, value) {
key.__weakmap__ = value;
return this;
}
/**
* Produces the `toString` result of `WeakMap`.
*
* @static
* @memberOf WeakMap
* @returns {string} Returns the string result.
*/
function toString() {
return nativeString;
}
WeakMap.toString = toString;
WeakMap.prototype.get = get;
WeakMap.prototype.set = set;
if (!root.WeakMap) {
context.WeakMap = WeakMap;
}
}
/*--------------------------------------------------------------------------*/
if (freeExports) {
freeExports.runInContext = runInContext;
} else {
runInContext(root);
}
}.call(this));

View File

@@ -1,12 +0,0 @@
self.console || (self.console = { 'log': function() {} });
addEventListener('message', function(e) {
if (e.data) {
try {
importScripts('../' + e.data);
} catch(e) {
self._ = { 'VERSION': e.message };
}
postMessage(_.VERSION);
}
}, false);

View File

@@ -3,139 +3,52 @@
<head>
<meta charset="utf-8">
<title>Backbone Test Suite</title>
<link rel="stylesheet" href="../node_modules/qunitjs/qunit/qunit.css">
<link rel="stylesheet" href="../vendor/qunit/qunit/qunit.css">
<style>
body > #qunit-header {
display: none;
}
</style>
</head>
<body>
<div id="qunit"></div>
<h1 id="qunit-header"></h1>
<div id="qunit-fixture">
<div id='testElement'>
<h1>Test</h1>
</div>
</div>
<script src="../vendor/json3/lib/json3.js"></script>
<script src="../vendor/jquery/jquery.js"></script>
<script src="../vendor/platform.js/platform.js"></script>
<script src="../vendor/qunit/qunit/qunit.js"></script>
<script src="test-ui.js"></script>
<script src="../lodash.js"></script>
<script>
// avoid reporting tests to Sauce Labs when script errors occur
if (location.port == '9001') {
window.onerror = function(message) {
if (window.QUnit) {
QUnit.config.done.length = 0;
}
global_test_results = { 'message': message };
};
}
</script>
<script src="../node_modules/qunitjs/qunit/qunit.js"></script>
<script src="../node_modules/qunit-extras/qunit-extras.js"></script>
<script src="../vendor/json-js/json2.js"></script>
<script src="../node_modules/platform/platform.js"></script>
<script src="./asset/test-ui.js"></script>
<script src="../lodash.src.js"></script>
<script>
var mixinPrereqs = (function() {
var lodash = _.noConflict();
return function(_) {
_.mixin({
'debounce': _.debounce || lodash.debounce,
'defer': _.defer || lodash.defer,
'pluck': _.pluck || lodash.pluck
});
};
}());
QUnit.config.asyncRetries = 10;
QUnit.config.hidepassed = true;
// load lodash
if (!ui.isModularize) {
document.write('<script src="' + ui.buildPath + '"><\/script>');
}
// load test scripts
document.write(ui.urlParams.loader != 'none'
? '<script data-dojo-config="async:1" src="' + ui.loaderPath + '"><\/script>'
: ([
'<script src="' + ui.buildPath + '"><\/script>',
'<script src="../node_modules/jquery/dist/jquery.js"><\/script>',
'<script src="../vendor/backbone/backbone.js"><\/script>',
'<script src="../vendor/backbone/test/environment.js"><\/script>',
'<script src="../vendor/backbone/test/noconflict.js"><\/script>',
'<script src="../vendor/backbone/test/events.js"><\/script>',
'<script src="../vendor/backbone/test/model.js"><\/script>',
'<script src="../vendor/backbone/test/collection.js"><\/script>',
'<script src="../vendor/backbone/test/router.js"><\/script>',
'<script src="../vendor/backbone/test/view.js"><\/script>',
'<script src="../vendor/backbone/test/sync.js"><\/script>'
].join('\n'))
);
var lodash = _.noConflict();
document.write('<script src="../' + ui.buildPath + '"><\/script>');
</script>
<script>
(function() {
if (window.curl) {
curl.config({ 'apiName': 'require' });
}
if (!window.require) {
mixinPrereqs(_);
return;
}
var reBasename = /[\w.-]+$/,
basePath = ('//' + location.host + location.pathname.replace(reBasename, '')).replace(/\btest\/$/, ''),
modulePath = ui.buildPath.replace(/\.js$/, ''),
locationPath = modulePath.replace(reBasename, '').replace(/^\/|\/$/g, ''),
moduleMain = modulePath.match(reBasename)[0],
uid = +new Date;
function getConfig() {
var result = {
'baseUrl': './',
'urlArgs': 't=' + uid++,
'waitSeconds': 0,
'paths': {
'backbone': '../vendor/backbone/backbone',
'jquery': '../node_modules/jquery/dist/jquery'
},
'packages': [{
'name': 'test',
'location': '../vendor/backbone/test',
'config': {
// work around no global being exported
'exports': 'QUnit',
'loader': 'curl/loader/legacy'
}
}]
};
if (ui.isModularize) {
result.packages.push({
'name': 'underscore',
'location': locationPath,
'main': moduleMain
});
} else {
result.paths.underscore = modulePath;
_.mixin({
'debounce': lodash.debounce,
'defer': lodash.defer
});
if (!_.chain) {
_.mixin({
'chain': function(value) {
return new _(value);
}
return result;
}
QUnit.config.autostart = false;
require(getConfig(), ['underscore', 'backbone'], function(lodash) {
mixinPrereqs(lodash);
if (ui.isModularize) {
window._ = lodash;
}
require(getConfig(), [
'test/environment',
'test/noconflict',
'test/events',
'test/model',
'test/collection',
'test/router',
'test/view',
'test/sync'
], function() {
QUnit.start();
});
});
}());
}
</script>
<script src="../vendor/backbone/backbone.js"></script>
<script src="../vendor/backbone/test/environment.js"></script>
<script src="../vendor/backbone/test/noconflict.js"></script>
<script src="../vendor/backbone/test/events.js"></script>
<script src="../vendor/backbone/test/model.js"></script>
<script src="../vendor/backbone/test/collection.js"></script>
<script src="../vendor/backbone/test/router.js"></script>
<script src="../vendor/backbone/test/view.js"></script>
<script src="../vendor/backbone/test/sync.js"></script>
</body>
</html>

View File

@@ -2,407 +2,78 @@
<html lang="en">
<head>
<meta charset="utf-8">
<title>lodash Test Suite</title>
<link rel="stylesheet" href="../node_modules/qunitjs/qunit/qunit.css">
<style>
#exports {
display: none;
}
</style>
<title>Lo-Dash Test Suite</title>
<link rel="stylesheet" href="../vendor/qunit/qunit/qunit.css">
</head>
<body>
<script>
// avoid reporting tests to Sauce Labs when script errors occur
if (location.port == '9001') {
window.onerror = function(message) {
if (window.QUnit) {
QUnit.config.done.length = 0;
}
global_test_results = { 'message': message };
};
}
</script>
<script src="../node_modules/qunitjs/qunit/qunit.js"></script>
<script src="../node_modules/qunit-extras/qunit-extras.js"></script>
<script src="../node_modules/platform/platform.js"></script>
<script src="./asset/set.js"></script>
<script src="./asset/weakmap.js"></script>
<script src="./asset/test-ui.js"></script>
<div id="qunit"></div>
<div id="exports"></div>
<script src="../vendor/platform.js/platform.js"></script>
<script src="../vendor/qunit/qunit/qunit.js"></script>
<script src="test-ui.js"></script>
<script>
var setProperty = (function() {
var _defineProperty = Object.defineProperty;
return function(object, key, value) {
try {
_defineProperty(object, key, {
'configurable': true,
'enumerable': false,
'writable': true,
'value': value
});
} catch(e) {
object[key] = value;
}
};
}());
// set a bad shim
Object._keys = Object.keys;
Object.keys = function() { return []; };
function addBizarroMethods() {
var funcProto = Function.prototype,
objectProto = Object.prototype,
stringProto = String.prototype;
var hasOwnProperty = objectProto.hasOwnProperty,
fnToString = funcProto.toString,
nativeString = fnToString.call(objectProto.toString),
noop = function() {},
parseInt = window.parseInt,
propertyIsEnumerable = objectProto.propertyIsEnumerable,
reToString = /toString/g,
whitespace = ' \t\x0B\f\xA0\ufeff\n\r\u2028\u2029\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000';
function constant(value) {
return function() {
return value;
};
}
function createToString(funcName) {
return constant(nativeString.replace(reToString, funcName));
}
// allow bypassing native checks
setProperty(funcProto, 'toString', (function() {
function wrapper() {
setProperty(funcProto, 'toString', fnToString);
var result = hasOwnProperty.call(this, 'toString') ? this.toString() : fnToString.call(this);
setProperty(funcProto, 'toString', wrapper);
return result;
}
return wrapper;
}()));
// add extensions
funcProto._method = noop;
// set bad shims
setProperty(Array, '_isArray', Array.isArray);
setProperty(Array, 'isArray', noop);
setProperty(Date, '_now', Date.now);
setProperty(Date, 'now', noop);
setProperty(Object, '_getOwnPropertySymbols', Object.getOwnPropertySymbols);
setProperty(Object, 'getOwnPropertySymbols', (function() {
function getOwnPropertySymbols() {
return [];
}
setProperty(getOwnPropertySymbols, 'toString', createToString('getOwnPropertySymbols'));
return getOwnPropertySymbols;
}()));
setProperty(Object, '_getPrototypeOf', Object.getPrototypeOf);
setProperty(Object, 'getPrototypeOf', noop);
setProperty(Object, '_keys', Object.keys);
setProperty(Object, 'keys', noop);
setProperty(objectProto, '_propertyIsEnumerable', propertyIsEnumerable);
setProperty(objectProto, 'propertyIsEnumerable', function(key) {
if (key == '1' && this && typeof this == 'object' &&
hasOwnProperty.call(this, 'callee') &&
!propertyIsEnumerable.call(this, 'callee') &&
this.length === 2 && this[0] === 1 && this[1] === 0) {
throw new Error;
}
return propertyIsEnumerable.call(this, key);
});
setProperty(Number, '_isFinite', Number.isFinite);
setProperty(Number, 'isFinite', noop);
setProperty(window, '_ArrayBuffer', window.ArrayBuffer);
if (window.ArrayBuffer && window.Uint8Array) {
ArrayBuffer = (function(_ArrayBuffer) {
function ArrayBuffer(byteLength) {
var buffer = new _ArrayBuffer(byteLength);
if (!byteLength) {
setProperty(buffer, 'slice', buffer.slice ? null : bufferSlice);
}
return buffer;
}
function bufferSlice() {
var newBuffer = new _ArrayBuffer(this.byteLength),
view = new Uint8Array(newBuffer);
view.set(new Uint8Array(this));
return newBuffer;
}
setProperty(ArrayBuffer, 'toString', createToString('ArrayBuffer'));
setProperty(bufferSlice, 'toString', createToString('slice'));
return ArrayBuffer;
}(_ArrayBuffer));
}
if (!window.Float64Array && window.Uint8Array) {
Float64Array = (function() {
function Float64Array(buffer, byteOffset, length) {
return arguments.length == 1
? new Uint8Array(buffer)
: new Uint8Array(buffer, byteOffset || 0, length || buffer.byteLength);
}
setProperty(Float64Array, 'BYTES_PER_ELEMENT', 8);
setProperty(Float64Array, 'toString', createToString('Float64Array'));
return Float64Array;
}());
}
setProperty(window, '_Set', window.Set);
setProperty(window, 'Set', noop);
setProperty(window, '_WeakMap', window.WeakMap);
setProperty(window, 'WeakMap', noop);
setProperty(window, '_parseInt', parseInt);
setProperty(window, 'parseInt', (function() {
var checkStr = whitespace + '08',
isFaked = parseInt(checkStr) != 8,
reHexPrefix = /^0[xX]/,
reTrim = RegExp('^[' + whitespace + ']+|[' + whitespace + ']+$');
return function(value, radix) {
if (value == checkStr && !isFaked) {
isFaked = true;
return 0;
}
value = String(value == null ? '' : value).replace(reTrim, '');
return parseInt(value, +radix || (reHexPrefix.test(value) ? 16 : 10));
};
}()));
// fake lack of DOM support
setProperty(document, '_createDocumentFragment', document.createDocumentFragment);
document.createDocumentFragment = noop;
// fake `WinRTError`
setProperty(window, 'WinRTError', Error);
// fake free variable `global`
setProperty(window, 'exports', window);
setProperty(window, 'global', window);
setProperty(window, 'module', {});
}
function removeBizarroMethods() {
var funcProto = Function.prototype,
objectProto = Object.prototype,
stringProto = String.prototype;
if (Array._isArray) {
setProperty(Array, 'isArray', Array._isArray);
} else {
delete Array.isArray;
}
if (Date._now) {
setProperty(Date, 'now', Date._now);
} else {
delete Date.now;
}
if (Object._getOwnPropertySymbols) {
setProperty(Object, 'getOwnPropertySymbols', Object._getOwnPropertySymbols);
} else {
delete Object.getOwnPropertySymbols;
}
if (Object._getPrototypeOf) {
setProperty(Object, 'getPrototypeOf', Object._getPrototypeOf);
} else {
delete Object.getPrototypeOf;
}
if (Object._keys) {
setProperty(Object, 'keys', Object._keys);
} else {
delete Object.keys;
}
if (Number._isFinite) {
setProperty(Number, 'isFinite', Number._isFinite);
} else {
delete Number.isFinite;
}
if (window._ArrayBuffer) {
ArrayBuffer = _ArrayBuffer;
}
setProperty(window, '_ArrayBuffer', undefined);
if (window._Set) {
Set = _Set;
}
setProperty(window, '_Set', undefined);
if (window._WeakMap) {
WeakMap = _WeakMap;
}
setProperty(window, '_WeakMap', undefined);
setProperty(window, 'parseInt', window._parseInt);
setProperty(window, '_parseInt', undefined);
document.createDocumentFragment = document._createDocumentFragment;
setProperty(document, '_createDocumentFragment', undefined);
setProperty(window, 'WinRTError', undefined);
setProperty(window, 'exports', undefined);
setProperty(window, 'global', undefined);
setProperty(window, 'module', undefined);
setProperty(objectProto, 'propertyIsEnumerable', objectProto._propertyIsEnumerable);
delete Array._isArray;
delete Date._now;
delete Object._getOwnPropertySymbols;
delete Object._getPrototypeOf;
delete Object._keys;
delete funcProto._method;
delete objectProto._propertyIsEnumerable;
}
// load lodash and expose it to the bad extensions/shims
if (!ui.isModularize) {
addBizarroMethods();
document.write('<script src="' + ui.buildPath + '"><\/script>');
}
// load Lo-Dash and expose it to the bad `Object.keys` shim
document.write('<script src="../' + ui.buildPath + '"><\/script>');
</script>
<script>
// store lodash to test for bad extensions/shims
if (!ui.isModularize) {
var lodashBizarro = window._;
window._ = undefined;
removeBizarroMethods();
}
// load test scripts
document.write((ui.isForeign || ui.urlParams.loader == 'none')
? '<script src="' + ui.buildPath + '"><\/script><script src="test.js"><\/script>'
: '<script data-dojo-config="async:1" src="' + ui.loaderPath + '"><\/script>'
// store Lo-Dash to test for bad shim detection
var lodashBadShim = _;
// restore nativeKeys
Object.keys = Object._keys;
delete Object._keys;
// load Lo-Dash again to overwrite the existing `_` value
document.write('<script src="../' + ui.buildPath + '"><\/script>');
// load test.js if not using require.js
document.write(QUnit.urlParams.norequire
? '<script src="test.js"><\/script>'
: '<script src="../vendor/requirejs/require.js"><\/script>'
);
</script>
<script>
// load Lo-Dash as a module
var lodashModule,
shimmedModule,
underscoreModule;
window.require && require(
(function() {
if (window.curl) {
curl.config({ 'apiName': 'require' });
}
if (ui.isForeign || !window.require) {
return;
}
var reBasename = /[\w.-]+$/,
basePath = ('//' + location.host + location.pathname.replace(reBasename, '')).replace(/\btest\/$/, ''),
modulePath = ui.buildPath.replace(/\.js$/, ''),
moduleMain = modulePath.match(reBasename)[0],
locationPath = modulePath.replace(reBasename, '').replace(/^\/|\/$/g, ''),
shimmedLocationPath = './abc/../' + locationPath,
underscoreLocationPath = './xyz/../' + locationPath,
uid = +new Date;
function getConfig() {
var result = {
'baseUrl': './',
'urlArgs': 't=' + uid++,
'waitSeconds': 0,
'paths': {},
'packages': [{
'name': 'test',
'location': basePath + 'test',
'main': 'test',
'config': {
// work around no global being exported
'exports': 'QUnit',
'loader': 'curl/loader/legacy'
}
}],
'shim': {
'shimmed': {
'exports': '_'
}
var modulePath = ui.buildPath.replace(/\.js$/, '');
return {
'baseUrl': '../vendor/requirejs/',
'urlArgs': 't=' + (+new Date),
'paths': {
'lodash': '../../' + modulePath,
'shimmed': './../../' + modulePath,
'underscore': '../underscore/../../' + modulePath
},
'shim': {
'shimmed': {
'exports': '_'
}
};
if (ui.isModularize) {
result.packages.push({
'name': 'lodash',
'location': locationPath,
'main': moduleMain
}, {
'name': 'shimmed',
'location': shimmedLocationPath,
'main': moduleMain
}, {
'name': 'underscore',
'location': underscoreLocationPath,
'main': moduleMain
});
} else {
result.paths.lodash = modulePath;
result.paths.shimmed = shimmedLocationPath + '/' + moduleMain;
result.paths.underscore = underscoreLocationPath + '/' + moduleMain;
}
return result;
};
}()),
['lodash', 'shimmed', 'underscore'], function(lodash, shimmed, underscore) {
if (lodash && lodash.noConflict) {
lodashModule = lodash.noConflict();
lodashModule.moduleName = 'lodash';
}
function loadTests() {
require(getConfig(), ['test'], function() {
QUnit.start();
});
if (shimmed.noConflict) {
shimmedModule = shimmed.noConflict();
shimmedModule.moduleName = 'shimmed';
}
function loadModulesAndTests() {
require(getConfig(), ['lodash', 'shimmed', 'underscore'], function(lodash, shimmed, underscore) {
lodashModule = lodash;
lodashModule.moduleName = 'lodash';
if (shimmed) {
shimmedModule = shimmed.result(shimmed, 'noConflict') || shimmed;
shimmedModule.moduleName = 'shimmed';
}
if (underscore) {
underscoreModule = underscore.result(underscore, 'noConflict') || underscore;
underscoreModule.moduleName = 'underscore';
}
if (ui.isModularize) {
window._ = lodash;
}
if (ui.isModularize) {
require(getConfig(), [
'lodash/internal/baseEach',
'lodash/internal/isIndex',
'lodash/internal/isIterateeCall',
'lodash/internal/isLength'
], function(baseEach, isIndex, isIterateeCall, isLength) {
lodash._baseEach = baseEach;
lodash._isIndex = isIndex;
lodash._isIterateeCall = isIterateeCall;
lodash._isLength = isLength;
loadTests();
});
} else {
loadTests();
}
});
if (underscore && underscore.noConflict) {
underscoreModule = underscore.noConflict();
underscoreModule.moduleName = 'underscore';
}
QUnit.config.autostart = false;
if (window.requirejs) {
addBizarroMethods();
require(getConfig(), ['lodash'], function(lodash) {
lodashBizarro = lodash.result(lodash, 'noConflict') || lodash;
delete requirejs.s.contexts._;
removeBizarroMethods();
loadModulesAndTests();
});
} else {
loadModulesAndTests();
}
}());
require(['test.js']);
});
// set a more readable browser name
window.onload = function() {
@@ -412,7 +83,7 @@
ua.innerHTML = platform;
clearInterval(timeoutId);
}
}, 16);
}, 15);
};
</script>
</body>

16
test/run-test.sh Normal file → Executable file
View File

@@ -1,14 +1,18 @@
cd "$(dirname "$0")"
echo "Testing in node..."
node test.js ../lodash.src.js
for cmd in rhino "rhino -require" ringo phantomjs; do
echo ""
for cmd in rhino narwhal ringo phantomjs; do
echo "Testing in $cmd..."
$cmd test.js ../lodash.src.js
$cmd test.js ../dist/lodash.compat.js && $cmd test.js ../dist/lodash.compat.min.js
echo ""
done
echo "Testing in node..."
node test.js ../dist/lodash.js && node test.js ../dist/lodash.min.js
echo ""
echo "Testing build..."
node test-build.js
echo ""
echo "Testing in a browser..."
open index.html

View File

@@ -1,930 +0,0 @@
#!/usr/bin/env node
'use strict';
/** Environment shortcut. */
var env = process.env;
if (env.TRAVIS_SECURE_ENV_VARS == 'false') {
console.log('Skipping Sauce Labs jobs; secure environment variables are unavailable');
process.exit(0);
}
/** Load Node.js modules. */
var EventEmitter = require('events').EventEmitter,
http = require('http'),
path = require('path'),
url = require('url'),
util = require('util');
/** Load other modules. */
var _ = require('../lodash.src.js'),
chalk = require('chalk'),
ecstatic = require('ecstatic'),
request = require('request'),
SauceTunnel = require('sauce-tunnel');
/** Used for Sauce Labs credentials. */
var accessKey = env.SAUCE_ACCESS_KEY,
username = env.SAUCE_USERNAME;
/** Used as the default maximum number of times to retry a job and tunnel. */
var maxJobRetries = 3,
maxTunnelRetries = 3;
/** Used as the static file server middleware. */
var mount = ecstatic({
'cache': 'no-cache',
'root': process.cwd()
});
/** Used as the list of ports supported by Sauce Connect. */
var ports = [
80, 443, 888, 2000, 2001, 2020, 2109, 2222, 2310, 3000, 3001, 3030, 3210,
3333, 4000, 4001, 4040, 4321, 4502, 4503, 4567, 5000, 5001, 5050, 5555, 5432,
6000, 6001, 6060, 6666, 6543, 7000, 7070, 7774, 7777, 8000, 8001, 8003, 8031,
8080, 8081, 8765, 8777, 8888, 9000, 9001, 9080, 9090, 9876, 9877, 9999, 49221,
55001
];
/** Used by `logInline` to clear previously logged messages. */
var prevLine = '';
/** Method shortcut. */
var push = Array.prototype.push;
/** Used to detect error messages. */
var reError = /(?:\be|E)rror\b/;
/** Used to detect valid job ids. */
var reJobId = /^[a-z0-9]{32}$/;
/** Used to display the wait throbber. */
var throbberDelay = 500,
waitCount = -1;
/**
* Used as Sauce Labs config values.
* See the [Sauce Labs documentation](https://docs.saucelabs.com/reference/test-configuration/)
* for more details.
*/
var advisor = getOption('advisor', false),
build = getOption('build', (env.TRAVIS_COMMIT || '').slice(0, 10)),
commandTimeout = getOption('commandTimeout', 90),
compatMode = getOption('compatMode', null),
customData = Function('return {' + getOption('customData', '').replace(/^\{|}$/g, '') + '}')(),
deviceOrientation = getOption('deviceOrientation', 'portrait'),
framework = getOption('framework', 'qunit'),
idleTimeout = getOption('idleTimeout', 60),
jobName = getOption('name', 'unit tests'),
maxDuration = getOption('maxDuration', 120),
port = ports[Math.min(_.sortedIndex(ports, getOption('port', 9001)), ports.length - 1)],
publicAccess = getOption('public', true),
queueTimeout = getOption('queueTimeout', 240),
recordVideo = getOption('recordVideo', true),
recordScreenshots = getOption('recordScreenshots', false),
runner = getOption('runner', 'test/index.html').replace(/^\W+/, ''),
runnerUrl = getOption('runnerUrl', 'http://localhost:' + port + '/' + runner),
statusInterval = getOption('statusInterval', 5),
tags = getOption('tags', []),
throttled = getOption('throttled', 10),
tunneled = getOption('tunneled', true),
tunnelId = getOption('tunnelId', 'tunnel_' + (env.TRAVIS_JOB_ID || 0)),
tunnelTimeout = getOption('tunnelTimeout', 120),
videoUploadOnPass = getOption('videoUploadOnPass', false);
/** Used to convert Sauce Labs browser identifiers to their formal names. */
var browserNameMap = {
'googlechrome': 'Chrome',
'iehta': 'Internet Explorer',
'ipad': 'iPad',
'iphone': 'iPhone'
};
/** List of platforms to load the runner on. */
var platforms = [
['Linux', 'android', '5.0'],
['Linux', 'android', '4.4'],
['Linux', 'android', '4.0'],
['Windows 8.1', 'firefox', '37'],
['Windows 8.1', 'firefox', '36'],
['Windows 8.1', 'firefox', '20'],
['Windows 8.1', 'chrome', '41'],
['Windows 8.1', 'chrome', '40'],
['Windows 8.1', 'internet explorer', '11'],
['Windows 8', 'internet explorer', '10'],
['Windows 7', 'internet explorer', '9'],
['Windows 7', 'internet explorer', '8'],
['Windows XP', 'internet explorer', '7'],
['Windows XP', 'internet explorer', '6'],
['Windows 7', 'opera', '12'],
['Windows 7', 'opera', '11'],
['OS X 10.9', 'ipad', '8.1'],
['OS X 10.6', 'ipad', '4'],
['OS X 10.10', 'safari', '8'],
['OS X 10.9', 'safari', '7'],
['OS X 10.8', 'safari', '6'],
['OS X 10.6', 'safari', '5']
];
/** Used to tailor the `platforms` array. */
var isAMD = _.includes(tags, 'amd'),
isBackbone = _.includes(tags, 'backbone'),
isModern = _.includes(tags, 'modern');
// The platforms to test IE compatibility modes.
if (compatMode) {
platforms = [
['Windows 8.1', 'internet explorer', '11'],
['Windows 8', 'internet explorer', '10'],
['Windows 7', 'internet explorer', '9'],
['Windows 7', 'internet explorer', '8']
];
}
// The platforms for AMD tests.
if (isAMD) {
platforms = _.filter(platforms, function(platform) {
var browser = browserName(platform[1]),
version = +platform[2];
switch (browser) {
case 'Android': return version >= 4.4;
case 'Opera': return version >= 10;
}
return true;
});
}
// The platforms for Backbone tests.
if (isBackbone) {
platforms = _.filter(platforms, function(platform) {
var browser = browserName(platform[1]),
version = +platform[2];
switch (browser) {
case 'Firefox': return version >= 4;
case 'iPad': return version >= 5;
case 'Opera': return version >= 12;
}
return true;
});
}
// The platforms for modern builds.
if (isModern) {
platforms = _.filter(platforms, function(platform) {
var browser = browserName(platform[1]),
version = +platform[2];
switch (browser) {
case 'Android': return version >= 4.1;
case 'Firefox': return version >= 10;
case 'Internet Explorer': return version >= 9;
case 'iPad': return version >= 6;
case 'Opera': return version >= 12;
case 'Safari': return version >= 6;
}
return true;
});
}
/** Used as the default `Job` options object. */
var jobOptions = {
'build': build,
'command-timeout': commandTimeout,
'custom-data': customData,
'device-orientation': deviceOrientation,
'framework': framework,
'idle-timeout': idleTimeout,
'max-duration': maxDuration,
'name': jobName,
'public': publicAccess,
'platforms': platforms,
'record-screenshots': recordScreenshots,
'record-video': recordVideo,
'sauce-advisor': advisor,
'tags': tags,
'url': runnerUrl,
'video-upload-on-pass': videoUploadOnPass
};
if (publicAccess === true) {
jobOptions['public'] = 'public';
}
if (tunneled) {
jobOptions['tunnel-identifier'] = tunnelId;
}
/*----------------------------------------------------------------------------*/
/**
* Resolves the formal browser name for a given Sauce Labs browser identifier.
*
* @private
* @param {string} identifier The browser identifier.
* @returns {string} Returns the formal browser name.
*/
function browserName(identifier) {
return browserNameMap[identifier] || capitalizeWords(identifier);
}
/**
* Capitalizes the first character of each word in `string`.
*
* @private
* @param {string} string The string to augment.
* @returns {string} Returns the augmented string.
*/
function capitalizeWords(string) {
return _.map(string.split(' '), _.capitalize).join(' ');
}
/**
* Gets the value for the given option name. If no value is available the
* `defaultValue` is returned.
*
* @private
* @param {string} name The name of the option.
* @param {*} defaultValue The default option value.
* @returns {*} Returns the option value.
*/
function getOption(name, defaultValue) {
var isArr = _.isArray(defaultValue);
return _.reduce(process.argv, function(result, value) {
if (isArr) {
value = optionToArray(name, value);
return _.isEmpty(value) ? result : value;
}
value = optionToValue(name, value);
return value == null ? result : value;
}, defaultValue);
}
/**
* Checks if `value` is a job ID.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a job ID, else `false`.
*/
function isJobId(value) {
return reJobId.test(value);
}
/**
* Writes an inline message to standard output.
*
* @private
* @param {string} [text=''] The text to log.
*/
function logInline(text) {
var blankLine = _.repeat(' ', _.size(prevLine));
prevLine = text = _.trunc(text, 40);
process.stdout.write(text + blankLine.slice(text.length) + '\r');
}
/**
* Writes the wait throbber to standard output.
*
* @private
*/
function logThrobber() {
logInline('Please wait' + _.repeat('.', (++waitCount % 3) + 1));
}
/**
* Converts a comma separated option value into an array.
*
* @private
* @param {string} name The name of the option to inspect.
* @param {string} string The options string.
* @returns {Array} Returns the new converted array.
*/
function optionToArray(name, string) {
return _.compact(_.invoke((optionToValue(name, string) || '').split(/, */), 'trim'));
}
/**
* Extracts the option value from an option string.
*
* @private
* @param {string} name The name of the option to inspect.
* @param {string} string The options string.
* @returns {string|undefined} Returns the option value, else `undefined`.
*/
function optionToValue(name, string) {
var result = string.match(RegExp('^' + name + '(?:=([\\s\\S]+))?$'));
if (result) {
result = _.result(result, 1);
result = result ? _.trim(result) : true;
}
if (result === 'false') {
return false;
}
return result || undefined;
}
/*----------------------------------------------------------------------------*/
/**
* The `Job#remove` and `Tunnel#stop` callback used by `Jobs#restart`
* and `Tunnel#restart` respectively.
*
* @private
*/
function onGenericRestart() {
this.restarting = false;
this.emit('restart');
this.start();
}
/**
* The `request.put` and `SauceTunnel#stop` callback used by `Jobs#stop`
* and `Tunnel#stop` respectively.
*
* @private
* @param {Object} [error] The error object.
*/
function onGenericStop(error) {
this.running = this.stopping = false;
this.emit('stop', error);
}
/**
* The `request.del` callback used by `Jobs#remove`.
*
* @private
*/
function onJobRemove(error, res, body) {
this.id = this.taskId = this.url = null;
this.removing = false;
this.emit('remove');
}
/**
* The `Job#remove` callback used by `Jobs#reset`.
*
* @private
*/
function onJobReset() {
this.attempts = 0;
this.failed = this.resetting = false;
this._pollerId = this.id = this.result = this.taskId = this.url = null;
this.emit('reset');
}
/**
* The `request.post` callback used by `Jobs#start`.
*
* @private
* @param {Object} [error] The error object.
* @param {Object} res The response data object.
* @param {Object} body The response body JSON object.
*/
function onJobStart(error, res, body) {
this.starting = false;
if (this.stopping) {
return;
}
var statusCode = _.result(res, 'statusCode'),
taskId = _.first(_.result(body, 'js tests'));
if (error || !taskId || statusCode != 200) {
if (this.attempts < this.retries) {
this.restart();
return;
}
var na = 'unavailable',
bodyStr = _.isObject(body) ? '\n' + JSON.stringify(body) : na,
statusStr = _.isFinite(statusCode) ? statusCode : na;
logInline();
console.error('Failed to start job; status: %s, body: %s', statusStr, bodyStr);
if (error) {
console.error(error);
}
this.failed = true;
this.emit('complete');
return;
}
this.running = true;
this.taskId = taskId;
this.timestamp = _.now();
this.emit('start');
this.status();
}
/**
* The `request.post` callback used by `Job#status`.
*
* @private
* @param {Object} [error] The error object.
* @param {Object} res The response data object.
* @param {Object} body The response body JSON object.
*/
function onJobStatus(error, res, body) {
this.checking = false;
if (!this.running || this.stopping) {
return;
}
var completed = _.result(body, 'completed', false),
data = _.first(_.result(body, 'js tests')),
elapsed = (_.now() - this.timestamp) / 1000,
jobId = _.result(data, 'job_id', null),
jobResult = _.result(data, 'result', null),
jobStatus = _.result(data, 'status', ''),
jobUrl = _.result(data, 'url', null),
expired = (elapsed >= queueTimeout && !_.includes(jobStatus, 'in progress')),
options = this.options,
platform = options.platforms[0];
if (_.isObject(jobResult)) {
var message = _.result(jobResult, 'message');
} else {
if (typeof jobResult == 'string') {
message = jobResult;
}
jobResult = null;
}
if (isJobId(jobId)) {
this.id = jobId;
this.result = jobResult;
this.url = jobUrl;
} else {
completed = false;
}
this.emit('status', jobStatus);
if (!completed && !expired) {
this._pollerId = _.delay(_.bind(this.status, this), this.statusInterval * 1000);
return;
}
var description = browserName(platform[1]) + ' ' + platform[2] + ' on ' + capitalizeWords(platform[0]),
errored = !jobResult || !jobResult.passed || reError.test(message) || reError.test(jobStatus),
failures = _.result(jobResult, 'failed'),
label = options.name + ':',
tunnel = this.tunnel;
if (errored || failures) {
if (errored && this.attempts < this.retries) {
this.restart();
return;
}
var details = 'See ' + jobUrl + ' for details.';
this.failed = true;
logInline();
if (failures) {
console.error(label + ' %s ' + chalk.red('failed') + ' %d test' + (failures > 1 ? 's' : '') + '. %s', description, failures, details);
}
else if (tunnel.attempts < tunnel.retries) {
tunnel.restart();
return;
}
else {
if (typeof message == 'undefined') {
message = 'Results are unavailable. ' + details;
}
console.error(label, description, chalk.red('failed') + ';', message);
}
}
else {
logInline();
console.log(label, description, chalk.green('passed'));
}
this.running = false;
this.emit('complete');
}
/**
* The `SauceTunnel#start` callback used by `Tunnel#start`.
*
* @private
* @param {boolean} success The connection success indicator.
*/
function onTunnelStart(success) {
this.starting = false;
if (this._timeoutId) {
clearTimeout(this._timeoutId);
this._timeoutId = null;
}
if (!success) {
if (this.attempts < this.retries) {
this.restart();
return;
}
logInline();
console.error('Failed to open Sauce Connect tunnel');
process.exit(2);
}
logInline();
console.log('Sauce Connect tunnel opened');
var jobs = this.jobs;
push.apply(jobs.queue, jobs.all);
this.running = true;
this.emit('start');
console.log('Starting jobs...');
this.dequeue();
}
/*----------------------------------------------------------------------------*/
/**
* The Job constructor.
*
* @private
* @param {Object} [properties] The properties to initialize a job with.
*/
function Job(properties) {
EventEmitter.call(this);
this.options = {};
_.merge(this, properties);
_.defaults(this.options, _.cloneDeep(jobOptions));
this.attempts = 0;
this.checking = this.failed = this.removing = this.resetting = this.restarting = this.running = this.starting = this.stopping = false;
this._pollerId = this.id = this.result = this.taskId = this.url = null;
}
util.inherits(Job, EventEmitter);
/**
* Removes the job.
*
* @memberOf Job
* @param {Function} callback The function called once the job is removed.
* @param {Object} Returns the job instance.
*/
Job.prototype.remove = function(callback) {
this.once('remove', _.callback(callback));
if (this.removing) {
return this;
}
this.removing = true;
return this.stop(function() {
var onRemove = _.bind(onJobRemove, this);
if (!this.id) {
_.defer(onRemove);
return;
}
request.del(_.template('https://saucelabs.com/rest/v1/${user}/jobs/${id}')(this), {
'auth': { 'user': this.user, 'pass': this.pass }
}, onRemove);
});
};
/**
* Resets the job.
*
* @memberOf Job
* @param {Function} callback The function called once the job is reset.
* @param {Object} Returns the job instance.
*/
Job.prototype.reset = function(callback) {
this.once('reset', _.callback(callback));
if (this.resetting) {
return this;
}
this.resetting = true;
return this.remove(onJobReset);
};
/**
* Restarts the job.
*
* @memberOf Job
* @param {Function} callback The function called once the job is restarted.
* @param {Object} Returns the job instance.
*/
Job.prototype.restart = function(callback) {
this.once('restart', _.callback(callback));
if (this.restarting) {
return this;
}
this.restarting = true;
var options = this.options,
platform = options.platforms[0],
description = browserName(platform[1]) + ' ' + platform[2] + ' on ' + capitalizeWords(platform[0]),
label = options.name + ':';
logInline();
console.log('%s %s restart %d of %d', label, description, ++this.attempts, this.retries);
return this.remove(onGenericRestart);
};
/**
* Starts the job.
*
* @memberOf Job
* @param {Function} callback The function called once the job is started.
* @param {Object} Returns the job instance.
*/
Job.prototype.start = function(callback) {
this.once('start', _.callback(callback));
if (this.starting || this.running) {
return this;
}
this.starting = true;
request.post(_.template('https://saucelabs.com/rest/v1/${user}/js-tests')(this), {
'auth': { 'user': this.user, 'pass': this.pass },
'json': this.options
}, _.bind(onJobStart, this));
return this;
};
/**
* Checks the status of a job.
*
* @memberOf Job
* @param {Function} callback The function called once the status is resolved.
* @param {Object} Returns the job instance.
*/
Job.prototype.status = function(callback) {
this.once('status', _.callback(callback));
if (this.checking || this.removing || this.resetting || this.restarting || this.starting || this.stopping) {
return this;
}
this._pollerId = null;
this.checking = true;
request.post(_.template('https://saucelabs.com/rest/v1/${user}/js-tests/status')(this), {
'auth': { 'user': this.user, 'pass': this.pass },
'json': { 'js tests': [this.taskId] }
}, _.bind(onJobStatus, this));
return this;
};
/**
* Stops the job.
*
* @memberOf Job
* @param {Function} callback The function called once the job is stopped.
* @param {Object} Returns the job instance.
*/
Job.prototype.stop = function(callback) {
this.once('stop', _.callback(callback));
if (this.stopping) {
return this;
}
this.stopping = true;
if (this._pollerId) {
clearTimeout(this._pollerId);
this._pollerId = null;
this.checking = false;
}
var onStop = _.bind(onGenericStop, this);
if (!this.running || !this.id) {
_.defer(onStop);
return this;
}
request.put(_.template('https://saucelabs.com/rest/v1/${user}/jobs/${id}/stop')(this), {
'auth': { 'user': this.user, 'pass': this.pass }
}, onStop);
return this;
};
/*----------------------------------------------------------------------------*/
/**
* The Tunnel constructor.
*
* @private
* @param {Object} [properties] The properties to initialize the tunnel with.
*/
function Tunnel(properties) {
EventEmitter.call(this);
_.merge(this, properties);
var active = [],
queue = [];
var all = _.map(this.platforms, function(platform) {
return new Job(_.merge({
'user': this.user,
'pass': this.pass,
'tunnel': this,
'options': { 'platforms': [platform] }
}, this.job));
}, this);
var completed = 0,
restarted = [],
success = true,
total = all.length,
tunnel = this;
_.invoke(all, 'on', 'complete', function() {
_.pull(active, this);
if (success) {
success = !this.failed;
}
if (++completed == total) {
tunnel.stop(_.partial(tunnel.emit, 'complete', success));
return;
}
tunnel.dequeue();
});
_.invoke(all, 'on', 'restart', function() {
if (!_.includes(restarted, this)) {
restarted.push(this);
}
// Restart tunnel if all active jobs have restarted.
var threshold = Math.min(all.length, _.isFinite(throttled) ? throttled : 3);
if (tunnel.attempts < tunnel.retries &&
active.length >= threshold && _.isEmpty(_.difference(active, restarted))) {
tunnel.restart();
}
});
this.on('restart', function() {
completed = 0;
success = true;
restarted.length = 0;
});
this._timeoutId = null;
this.attempts = 0;
this.restarting = this.running = this.starting = this.stopping = false;
this.jobs = { 'active': active, 'all': all, 'queue': queue };
this.connection = new SauceTunnel(this.user, this.pass, this.id, this.tunneled, ['-P', '0']);
}
util.inherits(Tunnel, EventEmitter);
/**
* Restarts the tunnel.
*
* @memberOf Tunnel
* @param {Function} callback The function called once the tunnel is restarted.
*/
Tunnel.prototype.restart = function(callback) {
this.once('restart', _.callback(callback));
if (this.restarting) {
return this;
}
this.restarting = true;
logInline();
console.log('Tunnel %s: restart %d of %d', this.id, ++this.attempts, this.retries);
var jobs = this.jobs,
active = jobs.active,
all = jobs.all;
var reset = _.after(all.length, _.bind(this.stop, this, onGenericRestart)),
stop = _.after(active.length, _.partial(_.invoke, all, 'reset', reset));
if (_.isEmpty(active)) {
_.defer(stop);
}
if (_.isEmpty(all)) {
_.defer(reset);
}
_.invoke(active, 'stop', function() {
_.pull(active, this);
stop();
});
if (this._timeoutId) {
clearTimeout(this._timeoutId);
this._timeoutId = null;
}
return this;
};
/**
* Starts the tunnel.
*
* @memberOf Tunnel
* @param {Function} callback The function called once the tunnel is started.
* @param {Object} Returns the tunnel instance.
*/
Tunnel.prototype.start = function(callback) {
this.once('start', _.callback(callback));
if (this.starting || this.running) {
return this;
}
this.starting = true;
logInline();
console.log('Opening Sauce Connect tunnel...');
var onStart = _.bind(onTunnelStart, this);
if (this.timeout) {
this._timeoutId = _.delay(onStart, this.timeout * 1000, false);
}
this.connection.start(onStart);
return this;
};
/**
* Removes jobs from the queue and starts them.
*
* @memberOf Tunnel
* @param {Object} Returns the tunnel instance.
*/
Tunnel.prototype.dequeue = function() {
var jobs = this.jobs,
active = jobs.active,
queue = jobs.queue,
throttled = this.throttled;
while (queue.length && (active.length < throttled)) {
active.push(queue.shift().start());
}
return this;
};
/**
* Stops the tunnel.
*
* @memberOf Tunnel
* @param {Function} callback The function called once the tunnel is stopped.
* @param {Object} Returns the tunnel instance.
*/
Tunnel.prototype.stop = function(callback) {
this.once('stop', _.callback(callback));
if (this.stopping) {
return this;
}
this.stopping = true;
logInline();
console.log('Shutting down Sauce Connect tunnel...');
var jobs = this.jobs,
active = jobs.active;
var stop = _.after(active.length, _.bind(function() {
var onStop = _.bind(onGenericStop, this);
if (this.running) {
this.connection.stop(onStop);
} else {
onStop();
}
}, this));
jobs.queue.length = 0;
if (_.isEmpty(active)) {
_.defer(stop);
}
_.invoke(active, 'stop', function() {
_.pull(active, this);
stop();
});
if (this._timeoutId) {
clearTimeout(this._timeoutId);
this._timeoutId = null;
}
return this;
};
/*----------------------------------------------------------------------------*/
// Cleanup any inline logs when exited via `ctrl+c`.
process.on('SIGINT', function() {
logInline();
process.exit();
});
// Create a web server for the current working directory.
http.createServer(function(req, res) {
// See http://msdn.microsoft.com/en-us/library/ff955275(v=vs.85).aspx.
if (compatMode && path.extname(url.parse(req.url).pathname) == '.html') {
res.setHeader('X-UA-Compatible', 'IE=' + compatMode);
}
mount(req, res);
}).listen(port);
// Setup Sauce Connect so we can use this server from Sauce Labs.
var tunnel = new Tunnel({
'user': username,
'pass': accessKey,
'id': tunnelId,
'job': { 'retries': maxJobRetries, 'statusInterval': statusInterval },
'platforms': platforms,
'retries': maxTunnelRetries,
'throttled': throttled,
'tunneled': tunneled,
'timeout': tunnelTimeout
});
tunnel.on('complete', function(success) {
process.exit(success ? 0 : 1);
});
tunnel.start();
setInterval(logThrobber, throbberDelay);

3
test/template/a.jst Normal file
View File

@@ -0,0 +1,3 @@
<ul>
<% _.forEach(people, function(name) { %><li><%- name %></li><% }); %>
</ul>

1
test/template/b.jst Normal file
View File

@@ -0,0 +1 @@
<% print("Hello " + epithet); %>.

1
test/template/c.jst Normal file
View File

@@ -0,0 +1 @@
Hello ${ name }!

1
test/template/d.tpl Normal file
View File

@@ -0,0 +1 @@
Hello {{ name }}!

1324
test/test-build.js Normal file

File diff suppressed because it is too large Load Diff

108
test/test-ui.js Normal file
View File

@@ -0,0 +1,108 @@
;(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);
/** The `ui` object */
var ui = {};
/*--------------------------------------------------------------------------*/
// expose Lo-Dash build file path
ui.buildPath = (function() {
switch (build) {
case 'lodash-prod': return 'dist/lodash.compat.min.js';
case 'lodash-underscore': return 'dist/lodash.underscore.min.js';
case 'lodash-modern': return 'dist/lodash.min.js';
case 'lodash-modern-debug': return 'dist/lodash.js';
case 'lodash-custom': return 'lodash.custom.min.js';
case 'lodash-custom-debug': return 'lodash.custom.js';
}
return 'lodash.js';
}());
// assign `QUnit.urlParams` properties
QUnit.extend(QUnit.urlParams, {
'build': build,
'norequire': norequire
});
// initialize controls
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=' + buildList[buildList.selectedIndex].value +
(checkbox.checked ? '&norequire=true' : '');
}
function init() {
var toolbar = document.getElementById('qunit-testrunner-toolbar');
if (toolbar) {
toolbar.appendChild(span1);
toolbar.appendChild(span2);
buildList.selectedIndex = (function() {
switch (build) {
case 'lodash-prod': return 1;
case 'lodash-underscore': return 2;
case 'lodash-modern': return 3;
case 'lodash-modern-debug': return 4;
case 'lodash-custom': return 5;
case 'lodash-custom-debug': return 6;
}
return 0;
}());
checkbox.checked = norequire;
addEvent(checkbox, 'click', eventHandler);
addEvent(buildList, 'change', eventHandler);
}
else {
setTimeout(init, 15);
}
}
var span1 = document.createElement('span');
span1.innerHTML =
'<input id="qunit-norequire" type="checkbox">' +
'<label for="qunit-norequire">No RequireJS</label>';
var span2 = document.createElement('span');
span2.style.cssText = 'float:right';
span2.innerHTML =
'<label for="qunit-build">Build: </label>' +
'<select id="qunit-build">' +
'<option value="lodash-dev">Developement</option>' +
'<option value="lodash-prod">Production</option>' +
'<option value="lodash-underscore">Underscore</option>' +
'<option value="lodash-modern">Modern</option>' +
'<option value="lodash-modern-debug">Modern (debug)</option>' +
'<option value="lodash-custom">Custom</option>' +
'<option value="lodash-custom-debug">Custom (debug)</option>' +
'</select>';
var checkbox = span1.firstChild,
buildList = span2.lastChild;
init();
});
// expose `ui`
window.ui = ui;
}(this));

17321
test/test.js

File diff suppressed because it is too large Load Diff

View File

@@ -3,7 +3,7 @@
<head>
<meta charset="utf-8">
<title>Underscore Test Suite</title>
<link rel="stylesheet" href="../node_modules/qunitjs/qunit/qunit.css">
<link rel="stylesheet" href="../vendor/qunit/qunit/qunit.css">
<style>
iframe {
display: none;
@@ -19,230 +19,79 @@
</div>
<img id="chart_image" src="data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==">
</div>
<script src="../vendor/jquery/jquery.js"></script>
<script src="../vendor/platform.js/platform.js"></script>
<script src="../vendor/qunit/qunit/qunit.js"></script>
<script src="test-ui.js"></script>
<script>
// avoid reporting tests to Sauce Labs when script errors occur
if (location.port == '9001') {
window.onerror = function(message) {
if (window.QUnit) {
QUnit.config.done.length = 0;
}
global_test_results = { 'message': message };
};
}
</script>
<script src="../node_modules/qunitjs/qunit/qunit.js"></script>
<script src="../node_modules/qunit-extras/qunit-extras.js"></script>
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script src="../node_modules/platform/platform.js"></script>
<script src="./asset/test-ui.js"></script>
<script>
QUnit.config.asyncRetries = 10;
QUnit.config.hidepassed = true;
// excuse tests we intentionally fail or those with problems
QUnit.config.excused = {
'Arrays': {
'drop': [
'alias for rest'
],
'first': [
'can pass an index to first',
'[1,2]',
'0'
],
'flatten': [
'Flattens empty arrays',
'can flatten nested arrays',
'can shallowly flatten nested arrays',
'works on an arguments object',
'can shallowly flatten arrays containing only other arrays'
],
'initial': [
'initial can take an index',
'initial can take a large index',
'initial works on arguments object'
],
'intersection': [
'can perform an OO-style intersection',
'returns an empty array when passed null as first argument',
'returns an empty array when passed null as argument beyond the first'
],
'last': [
'can pass an index to last',
'0'
],
'lastIndexOf': [
'[0,-1,-1]'
],
'rest': [
'working rest(0)',
'rest can take an index',
'works on arguments object'
],
'take': [
'alias for first'
]
},
'Chaining': {
'pop': true,
'shift': true,
'splice': true,
'reverse/concat/unshift/pop/map': [
'can chain together array functions.'
]
},
'Collections': {
'filter': [
'OO-filter'
],
'invoke': [
'handles null & undefined'
],
'map': [
'OO-style doubled numbers'
],
'Resistant to collection length and properties changing while iterating': [
'Died on test #50'
]
},
'Functions': {
'bind': [
'Died on test #2'
],
'bindAll': [
'throws an error for bindAll with no functions named'
],
'memoize': [
'{"bar":"BAR","foo":"FOO"}',
'Died on test #8'
],
'throttle repeatedly with results': true,
'more throttle does not trigger leading call when leading is set to false': true,
'throttle does not trigger trailing call when trailing is set to false': true,
'debounce asap': true
},
'Objects': {
'#1929 Typed Array constructors are functions': true,
'allKeys': true,
'extendOwn': true,
'mapObject': true,
'matcher': true,
'matcher ': true,
'extend': [
'extend copies all properties from source'
],
'isFinite': [
'Numeric strings are numbers',
'Number instances can be finite'
],
'isMatch': [
'inherited and own properties are checked on the test object',
'doesnt falsey match constructor on undefined/null'
],
'keys': [
'is not fooled by sparse arrays; see issue #95',
'[]'
],
'matches': [
'inherited and own properties are checked on the test object',
'doesnt fasley match constructor on undefined/null'
]
},
'Utility': {
'_.templateSettings.variable': [
'"x"'
],
'times': [
'works as a wrapper'
]
}
};
// only excuse in Sauce Labs (buggy Safari and timers)
if (!ui.isSauceLabs) {
delete QUnit.config.excused.Functions['throttle repeatedly with results'];
delete QUnit.config.excused.Functions['more throttle does not trigger leading call when leading is set to false'];
delete QUnit.config.excused.Functions['throttle does not trigger trailing call when trailing is set to false'];
delete QUnit.config.excused.Functions['debounce asap'];
}
// load test scripts
document.write(ui.urlParams.loader != 'none'
? '<script data-dojo-config="async:1" src="' + ui.loaderPath + '"><\/script>'
: ([
'<script src="' + ui.buildPath + '"><\/script>',
'<script src="../vendor/underscore/test/collections.js"><\/script>',
'<script src="../vendor/underscore/test/arrays.js"><\/script>',
'<script src="../vendor/underscore/test/functions.js"><\/script>',
'<script src="../vendor/underscore/test/objects.js"><\/script>',
'<script src="../vendor/underscore/test/utility.js"><\/script>',
'<script src="../vendor/underscore/test/chaining.js"><\/script>'
].join('\n'))
);
document.write('<script src="../' + ui.buildPath + '"><\/script>');
</script>
<script>
(function() {
if (window.curl) {
curl.config({ 'apiName': 'require' });
}
if (!window.require) {
var arrayProto = Array.prototype,
concat = arrayProto.concat,
pop = arrayProto.pop,
push = arrayProto.push,
slice = arrayProto.slice;
if (_.chain) {
return;
}
var reBasename = /[\w.-]+$/,
basePath = ('//' + location.host + location.pathname.replace(reBasename, '')).replace(/\btest\/$/, ''),
modulePath = ui.buildPath.replace(/\.js$/, ''),
locationPath = modulePath.replace(reBasename, '').replace(/^\/|\/$/g, ''),
moduleId = /\bunderscore\b/i.test(ui.buildPath) ? 'underscore' : 'lodash',
moduleMain = modulePath.match(reBasename)[0],
uid = +new Date;
_.mixin = function(object) {
_.forEach(_.functions(object), function(methodName) {
var func = _[methodName] = object[methodName];
_.prototype[methodName] = function() {
var args = [this.__wrapped__];
push.apply(args, arguments);
function getConfig() {
var result = {
'baseUrl': './',
'urlArgs': 't=' + uid++,
'waitSeconds': 0,
'paths': {},
'packages': [{
'name': 'test',
'location': '../vendor/underscore/test',
'config': {
// work around no global being exported
'exports': 'QUnit',
'loader': 'curl/loader/legacy'
var result = func.apply(_, args);
if (this.__chain__) {
result = new _(result);
result.__chain__ = true;
}
}]
};
return result;
};
});
};
if (ui.isModularize) {
result.packages.push({
'name': moduleId,
'location': locationPath,
'main': moduleMain
});
} else {
result.paths[moduleId] = modulePath;
_.mixin(_);
_.mixin({
'findWhere': _.find
});
_.chain = function(value) {
value = new _(value);
value.__chain__ = true;
return value;
};
_.prototype.chain = function() {
this.__chain__ = true;
return this;
};
_.prototype.concat = function() {
var result = concat.apply(this.__wrapped__, arguments);
if (this.__chain__) {
result = new _(result);
result.__chain__ = true;
}
return result;
}
};
QUnit.config.autostart = false;
require(getConfig(), [moduleId], function(lodash) {
if (ui.isModularize) {
window._ = lodash;
}
require(getConfig(), [
'test/collections',
'test/arrays',
'test/functions',
'test/objects',
'test/utility',
'test/chaining'
], function() {
QUnit.start();
});
});
_.prototype.pop = function() {
pop.apply(this.__wrapped__, arguments);
return this;
};
}());
</script>
<script src="../vendor/underscore/test/collections.js"></script>
<script src="../vendor/underscore/test/arrays.js"></script>
<script src="../vendor/underscore/test/functions.js"></script>
<script src="../vendor/underscore/test/objects.js"></script>
<script src="../vendor/underscore/test/utility.js"></script>
<script src="../vendor/underscore/test/chaining.js"></script>
<script type="text/html" id="template">
<%
// a comment

View File

@@ -1,4 +1,4 @@
Copyright (c) 2010-2014 Jeremy Ashkenas, DocumentCloud
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
@@ -19,4 +19,4 @@ 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.
OTHER DEALINGS IN THE SOFTWARE.

26
vendor/backbone/README.md vendored Normal file
View File

@@ -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

File diff suppressed because it is too large Load Diff

View File

@@ -1,10 +1,12 @@
(function() {
$(document).ready(function() {
var a, b, c, d, e, col, otherCol;
module("Backbone.Collection", {
module("Backbone.Collection", _.extend(new Environment, {
setup: function() {
Environment.prototype.setup.apply(this, arguments);
a = new Backbone.Model({id: 3, label: 'a'});
b = new Backbone.Model({id: 2, label: 'b'});
c = new Backbone.Model({id: 1, label: 'c'});
@@ -14,7 +16,7 @@
otherCol = new Backbone.Collection();
}
});
}));
test("new and sort", 9, function() {
var counter = 0;
@@ -60,37 +62,33 @@
strictEqual(collection.last().get('a'), 4);
});
test("get", 6, function() {
test("get", 5, function() {
equal(col.get(0), d);
equal(col.get(d.clone()), d);
equal(col.get(2), b);
equal(col.get({id: 1}), c);
equal(col.get(c.clone()), c);
equal(col.get(col.first().cid), col.first());
});
test("get with non-default ids", 5, function() {
test("get with non-default ids", 4, function() {
var col = new Backbone.Collection();
var MongoModel = Backbone.Model.extend({idAttribute: '_id'});
var MongoModel = Backbone.Model.extend({
idAttribute: '_id'
});
var model = new MongoModel({_id: 100});
col.add(model);
col.push(model);
equal(col.get(100), model);
equal(col.get(model.cid), model);
equal(col.get(model), model);
equal(col.get(101), void 0);
model.set({_id: 101});
equal(col.get(101), model);
var col2 = new Backbone.Collection();
col2.model = MongoModel;
col2.add(model.attributes);
equal(col2.get(model.clone()), col2.first());
var Col2 = Backbone.Collection.extend({ model: MongoModel });
var col2 = new Col2();
col2.push(model);
equal(col2.get({_id: 101}), model);
equal(col2.get(model.clone()), model);
});
test('get with "undefined" id', function() {
var collection = new Backbone.Collection([{id: 1}, {id: 'undefined'}]);
equal(collection.get(1).id, 1);
}),
test("update index when id changes", 4, function() {
test("update index when id changes", 3, function() {
var col = new Backbone.Collection();
col.add([
{id : 0, name : 'one'},
@@ -98,10 +96,9 @@
]);
var one = col.get(0);
equal(one.get('name'), 'one');
col.on('change:name', function (model) { ok(this.get(model)); });
one.set({name: 'dalmatians', id : 101});
one.set({id : 101});
equal(col.get(0), null);
equal(col.get(101).get('name'), 'dalmatians');
equal(col.get(101).get('name'), 'one');
});
test("at", 1, function() {
@@ -112,7 +109,7 @@
equal(col.pluck('label').join(' '), 'a b c d');
});
test("add", 14, function() {
test("add", 10, function() {
var added, opts, secondAdded;
added = opts = secondAdded = null;
e = new Backbone.Model({id: 10, label : 'e'});
@@ -141,18 +138,6 @@
equal(atCol.length, 4);
equal(atCol.at(1), e);
equal(atCol.last(), h);
var coll = new Backbone.Collection(new Array(2));
var addCount = 0;
coll.on('add', function(){
addCount += 1;
});
coll.add([undefined, f, g]);
equal(coll.length, 5);
equal(addCount, 3);
coll.add(new Array(4));
equal(coll.length, 9);
equal(addCount, 7);
});
test("add multiple models", 6, function() {
@@ -241,19 +226,6 @@
equal(col.at(0).get('value'), 2);
});
test("add with parse and merge", function() {
var collection = new Backbone.Collection();
collection.parse = function(attrs) {
return _.map(attrs, function(model) {
if (model.model) return model.model;
return model;
});
};
collection.add({id: 1});
collection.add({model: {id: 1, name: 'Alf'}}, {parse: true, merge: true});
equal(collection.first().get('name'), 'Alf');
});
test("add model to collection with sort()-style comparator", 3, function() {
var col = new Backbone.Collection;
col.comparator = function(a, b) {
@@ -304,39 +276,6 @@
equal(otherRemoved, null);
});
test("add and remove return values", 13, function() {
var Even = Backbone.Model.extend({
validate: function(attrs) {
if (attrs.id % 2 !== 0) return "odd";
}
});
var col = new Backbone.Collection;
col.model = Even;
var list = col.add([{id: 2}, {id: 4}], {validate: true});
equal(list.length, 2);
ok(list[0] instanceof Backbone.Model);
equal(list[1], col.last());
equal(list[1].get('id'), 4);
list = col.add([{id: 3}, {id: 6}], {validate: true});
equal(col.length, 3);
equal(list[0], false);
equal(list[1].get('id'), 6);
var result = col.add({id: 6});
equal(result.cid, list[1].cid);
result = col.remove({id: 6});
equal(col.length, 2);
equal(result.id, 6);
list = col.remove([{id: 2}, {id: 8}]);
equal(col.length, 1);
equal(list[0].get('id'), 2);
equal(list[1], null);
});
test("shift and pop", 2, function() {
var col = new Backbone.Collection([{a: 'a'}, {b: 'b'}, {c: 'c'}]);
equal(col.shift().get('a'), 'a');
@@ -423,7 +362,9 @@
test("model destroy removes from all collections", 3, function() {
var e = new Backbone.Model({id: 5, title: 'Othello'});
e.sync = function(method, model, options) { options.success(); };
e.sync = function(method, model, options) {
options.success(model, [], options);
};
var colE = new Backbone.Collection([e]);
var colF = new Backbone.Collection([e]);
e.destroy();
@@ -455,15 +396,6 @@
equal(this.syncArgs.options.parse, false);
});
test("fetch with an error response triggers an error event", 1, function () {
var collection = new Backbone.Collection();
collection.on('error', function () {
ok(true);
});
collection.sync = function (method, model, options) { options.error(); };
collection.fetch();
});
test("ensure fetch only parses once", 1, function() {
var collection = new Backbone.Collection;
var counter = 0;
@@ -473,7 +405,7 @@
};
collection.url = '/test';
collection.fetch();
this.syncArgs.options.success();
this.syncArgs.options.success([]);
equal(counter, 1);
});
@@ -487,7 +419,7 @@
equal(model.collection, collection);
});
test("create with validate:true enforces validation", 3, function() {
test("create with validate:true enforces validation", 1, function() {
var ValidatingModel = Backbone.Model.extend({
validate: function(attrs) {
return "fail";
@@ -497,10 +429,6 @@
model: ValidatingModel
});
var col = new ValidatingCollection();
col.on('invalid', function (collection, error, options) {
equal(error, "fail");
equal(options.validationError, 'fail');
});
equal(col.create({"foo":"bar"}, {validate:true}), false);
});
@@ -533,10 +461,9 @@
equal(JSON.stringify(col), '[{"id":3,"label":"a"},{"id":2,"label":"b"},{"id":1,"label":"c"},{"id":0,"label":"d"}]');
});
test("where and findWhere", 8, function() {
var model = new Backbone.Model({a: 1});
test("where", 6, function() {
var coll = new Backbone.Collection([
model,
{a: 1},
{a: 1},
{a: 1, b: 2},
{a: 2, b: 2},
@@ -548,21 +475,19 @@
equal(coll.where({b: 1}).length, 0);
equal(coll.where({b: 2}).length, 2);
equal(coll.where({a: 1, b: 2}).length, 1);
equal(coll.findWhere({a: 1}), model);
equal(coll.findWhere({a: 4}), void 0);
});
test("Underscore methods", 16, function() {
test("Underscore methods", 13, function() {
equal(col.map(function(model){ return model.get('label'); }).join(' '), 'a b c d');
equal(col.any(function(model){ return model.id === 100; }), false);
equal(col.any(function(model){ return model.id === 0; }), true);
equal(col.indexOf(b), 1);
equal(col.size(), 4);
equal(col.rest().length, 3);
ok(!_.include(col.rest(), a));
ok(_.include(col.rest(), d));
ok(!_.include(col.rest()), a);
ok(!_.include(col.rest()), d);
ok(!col.isEmpty());
ok(!_.include(col.without(d), d));
ok(!_.include(col.without(d)), d);
equal(col.max(function(model){ return model.id; }).id, 3);
equal(col.min(function(model){ return model.id; }).id, 0);
deepEqual(col.chain()
@@ -570,15 +495,23 @@
.map(function(o){ return o.id * 2; })
.value(),
[4, 0]);
deepEqual(col.difference([c, d]), [a, b]);
ok(col.include(col.sample()));
var first = col.first();
ok(col.indexBy('id')[first.id] === first);
});
test("reset", 16, function() {
test("sortedIndex", function () {
var model = new Backbone.Model({key: 2});
var collection = new (Backbone.Collection.extend({
comparator: 'key'
}))([model, {key: 1}]);
equal(collection.sortedIndex(model), 1);
equal(collection.sortedIndex(model, 'key'), 1);
equal(collection.sortedIndex(model, function (model) {
return model.get('key');
}), 1);
});
test("reset", 10, function() {
var resetCount = 0;
var models = col.models;
var models = col.models.slice();
col.on('reset', function() { resetCount += 1; });
col.reset([]);
equal(resetCount, 1);
@@ -593,31 +526,6 @@
equal(col.length, 4);
ok(col.last() !== d);
ok(_.isEqual(col.last().attributes, d.attributes));
col.reset();
equal(col.length, 0);
equal(resetCount, 4);
var f = new Backbone.Model({id: 20, label : 'f'});
col.reset([undefined, f]);
equal(col.length, 2);
equal(resetCount, 5);
col.reset(new Array(4));
equal(col.length, 4);
equal(resetCount, 6);
});
test ("reset with different values", function(){
var col = new Backbone.Collection({id: 1});
col.reset({id: 1, a: 1});
equal(col.get(1).get('a'), 1);
});
test("same references in reset", function() {
var model = new Backbone.Model({id: 1});
var collection = new Backbone.Collection({id: 1});
collection.reset(model);
equal(collection.get(1), model);
});
test("reset passes caller options", 3, function() {
@@ -794,7 +702,9 @@
test("#1447 - create with wait adds model.", 1, function() {
var collection = new Backbone.Collection;
var model = new Backbone.Model;
model.sync = function(method, model, options){ options.success(); };
model.sync = function(method, model, options){
options.success(model, [], options);
};
collection.on('add', function(){ ok(true); });
collection.create(model, {wait: true});
});
@@ -924,7 +834,7 @@
collection.reset([]);
});
test("set", function() {
test("update", function() {
var m1 = new Backbone.Model();
var m2 = new Backbone.Model({id: 2});
var m3 = new Backbone.Model();
@@ -942,24 +852,24 @@
});
// remove: false doesn't remove any models
c.set([], {remove: false});
c.update([], {remove: false});
strictEqual(c.length, 2);
// add: false doesn't add any models
c.set([m1, m2, m3], {add: false});
c.update([m1, m2, m3], {add: false});
strictEqual(c.length, 2);
// merge: false doesn't change any models
c.set([m1, {id: 2, a: 1}], {merge: false});
c.update([m1, {id: 2, a: 1}], {merge: false});
strictEqual(m2.get('a'), void 0);
// add: false, remove: false only merges existing models
c.set([m1, {id: 2, a: 0}, m3, {id: 4}], {add: false, remove: false});
c.update([m1, {id: 2, a: 0}, m3, {id: 4}], {add: false, remove: false});
strictEqual(c.length, 2);
strictEqual(m2.get('a'), 0);
// default options add/remove/merge as appropriate
c.set([{id: 2, a: 1}, m3]);
c.update([{id: 2, a: 1}, m3]);
strictEqual(c.length, 2);
strictEqual(m2.get('a'), 1);
@@ -967,23 +877,23 @@
c.off('remove').on('remove', function(model) {
ok(model === m2 || model === m3);
});
c.set([]);
c.update([]);
strictEqual(c.length, 0);
});
test("set with only cids", 3, function() {
test("update with only cids", 3, function() {
var m1 = new Backbone.Model;
var m2 = new Backbone.Model;
var c = new Backbone.Collection;
c.set([m1, m2]);
c.update([m1, m2]);
equal(c.length, 2);
c.set([m1]);
c.update([m1]);
equal(c.length, 1);
c.set([m1, m1, m1, m2, m2], {remove: false});
c.update([m1, m1, m1, m2, m2], {remove: false});
equal(c.length, 2);
});
test("set with only idAttribute", 3, function() {
test("update with only idAttribute", 3, function() {
var m1 = { _id: 1 };
var m2 = { _id: 2 };
var col = Backbone.Collection.extend({
@@ -992,15 +902,15 @@
})
});
var c = new col;
c.set([m1, m2]);
c.update([m1, m2]);
equal(c.length, 2);
c.set([m1]);
c.update([m1]);
equal(c.length, 1);
c.set([m1, m1, m1, m2, m2], {remove: false});
c.update([m1, m1, m1, m2, m2], {remove: false});
equal(c.length, 2);
});
test("set + merge with default values defined", function() {
test("update + merge with default values defined", function() {
var Model = Backbone.Model.extend({
defaults: {
key: 'value'
@@ -1010,78 +920,14 @@
var col = new Backbone.Collection([m], {model: Model});
equal(col.first().get('key'), 'value');
col.set({id: 1, key: 'other'});
col.update({id: 1, key: 'other'});
equal(col.first().get('key'), 'other');
col.set({id: 1, other: 'value'});
col.update({id: 1, other: 'value'});
equal(col.first().get('key'), 'other');
equal(col.length, 1);
});
test('merge without mutation', function () {
var Model = Backbone.Model.extend({
initialize: function (attrs, options) {
if (attrs.child) {
this.set('child', new Model(attrs.child, options), options);
}
}
});
var Collection = Backbone.Collection.extend({model: Model});
var data = [{id: 1, child: {id: 2}}];
var collection = new Collection(data);
equal(collection.first().id, 1);
collection.set(data);
equal(collection.first().id, 1);
collection.set([{id: 2, child: {id: 2}}].concat(data));
deepEqual(collection.pluck('id'), [2, 1]);
});
test("`set` and model level `parse`", function() {
var Model = Backbone.Model.extend({});
var Collection = Backbone.Collection.extend({
model: Model,
parse: function (res) { return _.pluck(res.models, 'model'); }
});
var model = new Model({id: 1});
var collection = new Collection(model);
collection.set({models: [
{model: {id: 1}},
{model: {id: 2}}
]}, {parse: true});
equal(collection.first(), model);
});
test("`set` data is only parsed once", function() {
var collection = new Backbone.Collection();
collection.model = Backbone.Model.extend({
parse: function (data) {
equal(data.parsed, void 0);
data.parsed = true;
return data;
}
});
collection.set({}, {parse: true});
});
test('`set` matches input order in the absence of a comparator', function () {
var one = new Backbone.Model({id: 1});
var two = new Backbone.Model({id: 2});
var three = new Backbone.Model({id: 3});
var collection = new Backbone.Collection([one, two, three]);
collection.set([{id: 3}, {id: 2}, {id: 1}]);
deepEqual(collection.models, [three, two, one]);
collection.set([{id: 1}, {id: 2}]);
deepEqual(collection.models, [one, two]);
collection.set([two, three, one]);
deepEqual(collection.models, [two, three, one]);
collection.set([{id: 1}, {id: 2}], {remove: false});
deepEqual(collection.models, [two, three, one]);
collection.set([{id: 1}, {id: 2}, {id: 3}], {merge: false});
deepEqual(collection.models, [one, two, three]);
collection.set([three, two, one, {id: 4}], {add: false});
deepEqual(collection.models, [one, two, three]);
});
test("#1894 - Push should not trigger a sort", 0, function() {
var Collection = Backbone.Collection.extend({
comparator: 'id',
@@ -1092,19 +938,12 @@
new Collection().push({id: 1});
});
test("#2428 - push duplicate models, return the correct one", 1, function() {
var col = new Backbone.Collection;
var model1 = col.push({id: 101});
var model2 = col.push({id: 101})
ok(model2.cid == model1.cid);
});
test("`set` with non-normal id", function() {
test("`update` with non-normal id", function() {
var Collection = Backbone.Collection.extend({
model: Backbone.Model.extend({idAttribute: '_id'})
});
var collection = new Collection({_id: 1});
collection.set([{_id: 1, a: 1}], {add: false});
collection.update([{_id: 1, a: 1}], {add: false});
equal(collection.first().get('a'), 1);
});
@@ -1116,7 +955,7 @@
new Collection().add({id: 1}, {sort: false});
});
test("#1915 - `parse` data in the right order in `set`", function() {
test("#1915 - `parse` data in the right order in `update`", function() {
var collection = new (Backbone.Collection.extend({
parse: function (data) {
strictEqual(data.status, 'ok');
@@ -1124,7 +963,7 @@
}
}));
var res = {status: 'ok', data:[{id: 1}]};
collection.set(res, {parse: true});
collection.update(res, {parse: true});
});
asyncTest("#1939 - `parse` is passed `options`", 1, function () {
@@ -1162,7 +1001,7 @@
test("`add` only `sort`s when necessary with comparator function", 3, function () {
var collection = new (Backbone.Collection.extend({
comparator: function(a, b) {
return a.get('a') > b.get('a') ? 1 : (a.get('a') < b.get('a') ? -1 : 0);
a.get('a') > b.get('a') ? 1 : (a.get('a') < b.get('a') ? -1 : 0);
}
}))([{id: 1}, {id: 2}, {id: 3}]);
collection.on('sort', function () { ok(true); });
@@ -1174,165 +1013,4 @@
collection.add(collection.models, {merge: true}); // don't sort
});
test("Attach options to collection.", 2, function() {
var model = new Backbone.Model;
var comparator = function(){};
var collection = new Backbone.Collection([], {
model: model,
comparator: comparator
});
ok(collection.model === model);
ok(collection.comparator === comparator);
});
test("`add` overrides `set` flags", function () {
var collection = new Backbone.Collection();
collection.once('add', function (model, collection, options) {
collection.add({id: 2}, options);
});
collection.set({id: 1});
equal(collection.length, 2);
});
test("#2606 - Collection#create, success arguments", 1, function() {
var collection = new Backbone.Collection;
collection.url = 'test';
collection.create({}, {
success: function(model, resp, options) {
strictEqual(resp, 'response');
}
});
this.ajaxSettings.success('response');
});
test("#2612 - nested `parse` works with `Collection#set`", function() {
var Job = Backbone.Model.extend({
constructor: function() {
this.items = new Items();
Backbone.Model.apply(this, arguments);
},
parse: function(attrs) {
this.items.set(attrs.items, {parse: true});
return _.omit(attrs, 'items');
}
});
var Item = Backbone.Model.extend({
constructor: function() {
this.subItems = new Backbone.Collection();
Backbone.Model.apply(this, arguments);
},
parse: function(attrs) {
this.subItems.set(attrs.subItems, {parse: true});
return _.omit(attrs, 'subItems');
}
});
var Items = Backbone.Collection.extend({
model: Item
});
var data = {
name: 'JobName',
id: 1,
items: [{
id: 1,
name: 'Sub1',
subItems: [
{id: 1, subName: 'One'},
{id: 2, subName: 'Two'}
]
}, {
id: 2,
name: 'Sub2',
subItems: [
{id: 3, subName: 'Three'},
{id: 4, subName: 'Four'}
]
}]
};
var newData = {
name: 'NewJobName',
id: 1,
items: [{
id: 1,
name: 'NewSub1',
subItems: [
{id: 1,subName: 'NewOne'},
{id: 2,subName: 'NewTwo'}
]
}, {
id: 2,
name: 'NewSub2',
subItems: [
{id: 3,subName: 'NewThree'},
{id: 4,subName: 'NewFour'}
]
}]
};
var job = new Job(data, {parse: true});
equal(job.get('name'), 'JobName');
equal(job.items.at(0).get('name'), 'Sub1');
equal(job.items.length, 2);
equal(job.items.get(1).subItems.get(1).get('subName'), 'One');
equal(job.items.get(2).subItems.get(3).get('subName'), 'Three');
job.set(job.parse(newData, {parse: true}));
equal(job.get('name'), 'NewJobName');
equal(job.items.at(0).get('name'), 'NewSub1');
equal(job.items.length, 2);
equal(job.items.get(1).subItems.get(1).get('subName'), 'NewOne');
equal(job.items.get(2).subItems.get(3).get('subName'), 'NewThree');
});
test('_addReference binds all collection events & adds to the lookup hashes', 9, function() {
var calls = {add: 0, remove: 0};
var Collection = Backbone.Collection.extend({
_addReference: function(model) {
Backbone.Collection.prototype._addReference.apply(this, arguments);
calls.add++;
equal(model, this._byId[model.id]);
equal(model, this._byId[model.cid]);
equal(model._events.all.length, 1);
},
_removeReference: function(model) {
Backbone.Collection.prototype._removeReference.apply(this, arguments);
calls.remove++;
equal(this._byId[model.id], void 0);
equal(this._byId[model.cid], void 0);
equal(model.collection, void 0);
equal(model._events.all, void 0);
}
});
var collection = new Collection();
var model = collection.add({id: 1});
collection.remove(model);
equal(calls.add, 1);
equal(calls.remove, 1);
});
test('Do not allow duplicate models to be `add`ed or `set`', function() {
var c = new Backbone.Collection();
c.add([{id: 1}, {id: 1}]);
equal(c.length, 1);
equal(c.models.length, 1);
c.set([{id: 1}, {id: 1}]);
equal(c.length, 1);
equal(c.models.length, 1);
});
})();
});

View File

@@ -1,43 +1,45 @@
(function() {
var sync = Backbone.sync;
var ajax = Backbone.ajax;
var emulateHTTP = Backbone.emulateHTTP;
var emulateJSON = Backbone.emulateJSON;
var history = window.history;
var pushState = history.pushState;
var replaceState = history.replaceState;
var Environment = this.Environment = function(){};
QUnit.testStart(function() {
var env = QUnit.config.current.testEnvironment;
_.extend(Environment.prototype, {
// We never want to actually call these during tests.
history.pushState = history.replaceState = function(){};
ajax: Backbone.ajax,
// Capture ajax settings for comparison.
Backbone.ajax = function(settings) {
env.ajaxSettings = settings;
};
sync: Backbone.sync,
// Capture the arguments to Backbone.sync for comparison.
Backbone.sync = function(method, model, options) {
env.syncArgs = {
method: method,
model: model,
options: options
emulateHTTP: Backbone.emulateHTTP,
emulateJSON: Backbone.emulateJSON,
setup: function() {
var env = this;
// Capture ajax settings for comparison.
Backbone.ajax = function(settings) {
env.ajaxSettings = settings;
};
sync.apply(this, arguments);
};
});
// Capture the arguments to Backbone.sync for comparison.
Backbone.sync = function(method, model, options) {
env.syncArgs = {
method: method,
model: model,
options: options
};
env.sync.apply(this, arguments);
};
},
teardown: function() {
this.syncArgs = null;
this.ajaxSettings = null;
Backbone.sync = this.sync;
Backbone.ajax = this.ajax;
Backbone.emulateHTTP = this.emulateHTTP;
Backbone.emulateJSON = this.emulateJSON;
}
QUnit.testDone(function() {
Backbone.sync = sync;
Backbone.ajax = ajax;
Backbone.emulateHTTP = emulateHTTP;
Backbone.emulateJSON = emulateJSON;
history.pushState = pushState;
history.replaceState = replaceState;
});
})();

View File

@@ -1,4 +1,4 @@
(function() {
$(document).ready(function() {
module("Backbone.Events");
@@ -99,43 +99,6 @@
a.listenTo(b, 'event2', cb);
a.stopListening(null, {event: cb});
b.trigger('event event2');
b.off();
a.listenTo(b, 'event event2', cb);
a.stopListening(null, 'event');
a.stopListening();
b.trigger('event2');
});
test("listenToOnce and stopListening", 1, function() {
var a = _.extend({}, Backbone.Events);
var b = _.extend({}, Backbone.Events);
a.listenToOnce(b, 'all', function() { ok(true); });
b.trigger('anything');
b.trigger('anything');
a.listenToOnce(b, 'all', function() { ok(false); });
a.stopListening();
b.trigger('anything');
});
test("listenTo, listenToOnce and stopListening", 1, function() {
var a = _.extend({}, Backbone.Events);
var b = _.extend({}, Backbone.Events);
a.listenToOnce(b, 'all', function() { ok(true); });
b.trigger('anything');
b.trigger('anything');
a.listenTo(b, 'all', function() { ok(false); });
a.stopListening();
b.trigger('anything');
});
test("listenTo and stopListening with event maps", 1, function() {
var a = _.extend({}, Backbone.Events);
var b = _.extend({}, Backbone.Events);
a.listenTo(b, {change: function(){ ok(true); }});
b.trigger('change');
a.listenTo(b, {change: function(){ ok(false); }});
a.stopListening();
b.trigger('change');
});
test("listenTo yourself", 1, function(){
@@ -152,31 +115,6 @@
e.trigger("foo");
});
test("stopListening cleans up references", 4, function() {
var a = _.extend({}, Backbone.Events);
var b = _.extend({}, Backbone.Events);
var fn = function() {};
a.listenTo(b, 'all', fn).stopListening();
equal(_.size(a._listeningTo), 0);
a.listenTo(b, 'all', fn).stopListening(b);
equal(_.size(a._listeningTo), 0);
a.listenTo(b, 'all', fn).stopListening(null, 'all');
equal(_.size(a._listeningTo), 0);
a.listenTo(b, 'all', fn).stopListening(null, null, fn);
equal(_.size(a._listeningTo), 0);
});
test("listenTo and stopListening cleaning up references", 2, function() {
var a = _.extend({}, Backbone.Events);
var b = _.extend({}, Backbone.Events);
a.listenTo(b, 'all', function(){ ok(true); });
b.trigger('anything');
a.listenTo(b, 'other', function(){ ok(false); });
a.stopListening(b, 'other');
a.stopListening(b, 'all');
equal(_.keys(a._listeningTo).length, 0);
});
test("listenTo with empty callback doesn't throw an error", 1, function(){
var e = _.extend({}, Backbone.Events);
e.listenTo(e, "foo", null);
@@ -303,13 +241,6 @@
_.extend({}, Backbone.Events).on('test').trigger('test');
});
test("if callback is truthy but not a function, `on` should throw an error just like jQuery", 1, function() {
var view = _.extend({}, Backbone.Events).on('test', 'noop');
raises(function() {
view.trigger('test');
});
});
test("remove all events for a specific context", 4, function() {
var obj = _.extend({}, Backbone.Events);
obj.on('x y all', function() { ok(true); });
@@ -328,6 +259,18 @@
obj.trigger('x y');
});
test("off is chainable", 3, function() {
var obj = _.extend({}, Backbone.Events);
// With no events
ok(obj.off() === obj);
// When removing all events
obj.on('event', function(){}, obj);
ok(obj.off() === obj);
// When removing some events
obj.on('event', function(){}, obj);
ok(obj.off('event') === obj);
});
test("#1310 - off does not skip consecutive events", 0, function() {
var obj = _.extend({}, Backbone.Events);
obj.on('event', function() { ok(false); }, obj);
@@ -457,21 +400,4 @@
_.extend({}, Backbone.Events).once('event').trigger('event');
});
test("event functions are chainable", function() {
var obj = _.extend({}, Backbone.Events);
var obj2 = _.extend({}, Backbone.Events);
var fn = function() {};
equal(obj, obj.trigger('noeventssetyet'));
equal(obj, obj.off('noeventssetyet'));
equal(obj, obj.stopListening('noeventssetyet'));
equal(obj, obj.on('a', fn));
equal(obj, obj.once('c', fn));
equal(obj, obj.trigger('a'));
equal(obj, obj.listenTo(obj2, 'a', fn));
equal(obj, obj.listenToOnce(obj2, 'b', fn));
equal(obj, obj.off('a c'));
equal(obj, obj.stopListening(obj2, 'a'));
equal(obj, obj.stopListening());
});
})();
});

View File

@@ -1,4 +1,4 @@
(function() {
$(document).ready(function() {
var proxy = Backbone.Model.extend();
var klass = Backbone.Collection.extend({
@@ -6,9 +6,10 @@
});
var doc, collection;
module("Backbone.Model", {
module("Backbone.Model", _.extend(new Environment, {
setup: function() {
Environment.prototype.setup.apply(this, arguments);
doc = new proxy({
id : '1-the-tempest',
title : "The Tempest",
@@ -19,7 +20,7 @@
collection.add(doc);
}
});
}));
test("initialize", 3, function() {
var Model = Backbone.Model.extend({
@@ -45,9 +46,9 @@
test("initialize with parsed attributes", 1, function() {
var Model = Backbone.Model.extend({
parse: function(attrs) {
attrs.value += 1;
return attrs;
parse: function(obj) {
obj.value += 1;
return obj;
}
});
var model = new Model({value: 1}, {parse: true});
@@ -68,8 +69,8 @@
test("parse can return null", 1, function() {
var Model = Backbone.Model.extend({
parse: function(attrs) {
attrs.value += 1;
parse: function(obj) {
obj.value += 1;
return null;
}
});
@@ -110,16 +111,6 @@
equal(model.url(), '/nested/1/collection/2');
});
test("underscore methods", 5, function() {
var model = new Backbone.Model({ 'foo': 'a', 'bar': 'b', 'baz': 'c' });
var model2 = model.clone();
deepEqual(model.keys(), ['foo', 'bar', 'baz']);
deepEqual(model.values(), ['a', 'b', 'c']);
deepEqual(model.invert(), { 'a': 'foo', 'b': 'bar', 'c': 'baz' });
deepEqual(model.pick('foo', 'baz'), {'foo': 'a', 'baz': 'c'});
deepEqual(model.omit('foo', 'bar'), {'baz': 'c'});
});
test("clone", 10, function() {
var a = new Backbone.Model({ 'foo': 1, 'bar': 2, 'baz': 3});
var b = a.clone();
@@ -262,26 +253,6 @@
model.set({result: void 0});
});
test("nested set triggers with the correct options", function() {
var model = new Backbone.Model();
var o1 = {};
var o2 = {};
var o3 = {};
model.on('change', function(__, options) {
switch (model.get('a')) {
case 1:
equal(options, o1);
return model.set('a', 2, o2);
case 2:
equal(options, o2);
return model.set('a', 3, o3);
case 3:
equal(options, o3);
}
});
model.set('a', 1, o1);
});
test("multiple unsets", 1, function() {
var i = 0;
var counter = function(){ i++; };
@@ -353,7 +324,7 @@
"two": 2
}
});
var model = new Defaulted({two: undefined});
var model = new Defaulted({two: null});
equal(model.get('one'), 1);
equal(model.get('two'), 2);
Defaulted = Backbone.Model.extend({
@@ -364,7 +335,7 @@
};
}
});
model = new Defaulted({two: undefined});
model = new Defaulted({two: null});
equal(model.get('one'), 3);
equal(model.get('two'), 4);
});
@@ -430,7 +401,7 @@
if (attrs.admin) return "Can't change admin status.";
};
model.sync = function(method, model, options) {
options.success.call(this, {admin: true});
options.success.call(this, this, {admin: true}, options);
};
model.on('invalid', function(model, error) {
lastError = error;
@@ -447,19 +418,6 @@
ok(_.isEqual(this.syncArgs.model, doc));
});
test("save, fetch, destroy triggers error event when an error occurs", 3, function () {
var model = new Backbone.Model();
model.on('error', function () {
ok(true);
});
model.sync = function (method, model, options) {
options.error();
};
model.save({data: 2, id: 1});
model.fetch();
model.destroy();
});
test("save with PATCH", function() {
doc.clear().set({id: 1, a: 1, b: 2, c: 3, d: 4});
doc.save();
@@ -477,7 +435,7 @@
test("save in positional style", 1, function() {
var model = new Backbone.Model();
model.sync = function(method, model, options) {
options.success();
options.success(model, {}, options);
};
model.save('title', 'Twelfth Night');
equal(model.get('title'), 'Twelfth Night');
@@ -486,8 +444,8 @@
test("save with non-object success response", 2, function () {
var model = new Backbone.Model();
model.sync = function(method, model, options) {
options.success('', options);
options.success(null, options);
options.success(model, '', options);
options.success(model, null, options);
};
model.save({testing:'empty'}, {
success: function (model) {
@@ -724,22 +682,6 @@
ok(this.syncArgs.model === model);
});
test("save without `wait` doesn't set invalid attributes", function () {
var model = new Backbone.Model();
model.validate = function () { return 1; }
model.save({a: 1});
equal(model.get('a'), void 0);
});
test("save doesn't validate twice", function () {
var model = new Backbone.Model();
var times = 0;
model.sync = function () {};
model.validate = function () { ++times; }
model.save({});
equal(times, 1);
});
test("`hasChanged` for falsey keys", 2, function() {
var model = new Backbone.Model();
model.set({x: true}, {silent: true});
@@ -778,7 +720,7 @@
test("#1030 - `save` with `wait` results in correct attributes if success is called during sync", 2, function() {
var model = new Backbone.Model({x: 1, y: 2});
model.sync = function(method, model, options) {
options.success();
options.success(model, {}, options);
};
model.on("change:x", function() { ok(true); });
model.save({x: 3}, {wait: true});
@@ -951,7 +893,7 @@
}
};
model.sync = function(method, model, options) {
options.success();
options.success(model, {}, options);
};
model.save({id: 1}, opts);
model.fetch(opts);
@@ -960,8 +902,9 @@
test("#1412 - Trigger 'sync' event.", 3, function() {
var model = new Backbone.Model({id: 1});
model.sync = function (method, model, options) { options.success(); };
model.url = '/test';
model.on('sync', function(){ ok(true); });
Backbone.ajax = function(settings){ settings.success(); };
model.fetch();
model.save();
model.destroy();
@@ -1007,7 +950,7 @@
var Model = Backbone.Model.extend({
sync: function(method, model, options) {
setTimeout(function(){
options.success();
options.success(model, {}, options);
start();
}, 0);
}
@@ -1127,4 +1070,4 @@
model.set({a: true});
});
})();
});

View File

@@ -1,4 +1,4 @@
(function() {
$(document).ready(function() {
module("Backbone.noConflict");
@@ -9,4 +9,4 @@
equal(window.Backbone, noconflictBackbone, 'Backbone is still pointing to the original Backbone');
});
})();
});

View File

@@ -1,14 +1,14 @@
(function() {
$(document).ready(function() {
var router = null;
var location = null;
var lastRoute = null;
var lastArgs = [];
var onRoute = function(router, route, args) {
function onRoute(router, route, args) {
lastRoute = route;
lastArgs = args;
};
}
var Location = function(href) {
this.replace(href);
@@ -16,11 +16,8 @@
_.extend(Location.prototype, {
parser: document.createElement('a'),
replace: function(href) {
this.parser.href = href;
_.extend(this, _.pick(this.parser,
_.extend(this, _.pick($('<a></a>', {href: href})[0],
'href',
'hash',
'host',
@@ -60,15 +57,6 @@
});
var ExternalObject = {
value: 'unset',
routingFunction: function(value) {
this.value = value;
}
};
_.bindAll(ExternalObject, 'routingFunction');
var Router = Backbone.Router.extend({
count: 0,
@@ -78,8 +66,6 @@
"counter": "counter",
"search/:query": "search",
"search/:query/p:page": "search",
"charñ": "charUTF",
"char%C3%B1": "charEscaped",
"contacts": "contacts",
"contacts/new": "newContact",
"contacts/:id": "loadContact",
@@ -87,11 +73,8 @@
"optional(/:item)": "optionalItem",
"named/optional/(y:z)": "namedOptional",
"splat/*args/end": "splat",
":repo/compare/*from...*to": "github",
"decode/:named/*splat": "decode",
"*first/complex-*part/*rest": "complex",
"query/:entity": "query",
"function/:value": ExternalObject.routingFunction,
"*first/complex-:part/*rest": "complex",
":entity?*args": "query",
"*anything": "anything"
},
@@ -108,19 +91,11 @@
this.count++;
},
search: function(query, page) {
search : function(query, page) {
this.query = query;
this.page = page;
},
charUTF: function() {
this.charType = 'UTF';
},
charEscaped: function() {
this.charType = 'escaped';
},
contacts: function(){
this.contact = 'index';
},
@@ -141,12 +116,6 @@
this.args = args;
},
github: function(repo, from, to) {
this.repo = repo;
this.from = from;
this.to = to;
},
complex: function(first, part, rest) {
this.first = first;
this.part = part;
@@ -166,11 +135,6 @@
this.z = z;
},
decode: function(named, path) {
this.named = named;
this.path = path;
},
routeEvent: function(arg) {
}
@@ -189,15 +153,6 @@
equal(lastArgs[0], 'news');
});
test("routes (simple, but unicode)", 4, function() {
location.replace('http://example.com#search/тест');
Backbone.history.checkUrl();
equal(router.query, "тест");
equal(router.page, void 0);
equal(lastRoute, 'search');
equal(lastArgs[0], "тест");
});
test("routes (two part)", 2, function() {
location.replace('http://example.com#search/nyc/p10');
Backbone.history.checkUrl();
@@ -211,21 +166,12 @@
equal(router.page, '20');
});
test("routes via navigate with params", 1, function() {
Backbone.history.navigate('query/test?a=b', {trigger: true});
equal(router.queryArgs, 'a=b');
});
test("routes via navigate for backwards-compatibility", 2, function() {
Backbone.history.navigate('search/manhattan/p20', true);
equal(router.query, 'manhattan');
equal(router.page, '20');
});
test("reports matched route via nagivate", 1, function() {
ok(Backbone.history.navigate('search/manhattan/p20', true));
});
test("route precedence via navigate", 6, function(){
// check both 0.9.x and backwards-compatibility options
_.each([ { trigger: true }, true ], function( options ){
@@ -267,14 +213,6 @@
equal(router.args, 'long-list/of/splatted_99args');
});
test("routes (github)", 3, function() {
location.replace('http://example.com#backbone/compare/1.0...braddunbar:with/slash');
Backbone.history.checkUrl();
equal(router.repo, 'backbone');
equal(router.from, '1.0');
equal(router.to, 'braddunbar:with/slash');
});
test("routes (optional)", 2, function() {
location.replace('http://example.com#optional');
Backbone.history.checkUrl();
@@ -293,7 +231,7 @@
});
test("routes (query)", 5, function() {
location.replace('http://example.com#query/mandel?a=b&c=d');
location.replace('http://example.com#mandel?a=b&c=d');
Backbone.history.checkUrl();
equal(router.entity, 'mandel');
equal(router.queryArgs, 'a=b&c=d');
@@ -308,23 +246,6 @@
equal(router.anything, 'doesnt-match-a-route');
});
test("routes (function)", 3, function() {
router.on('route', function(name) {
ok(name === '');
});
equal(ExternalObject.value, 'unset');
location.replace('http://example.com#function/set');
Backbone.history.checkUrl();
equal(ExternalObject.value, 'set');
});
test("Decode named parameters, not splats.", 2, function() {
location.replace('http://example.com#decode/a%2Fb/c%2Fd/e');
Backbone.history.checkUrl();
strictEqual(router.named, 'a/b');
strictEqual(router.path, 'c/d/e');
});
test("fires event when router doesn't have callback on it", 1, function() {
router.on("route:noCallback", function(){ ok(true); });
location.replace('http://example.com#noCallback');
@@ -356,9 +277,9 @@
test("#967 - Route callback gets passed encoded values.", 3, function() {
var route = 'has%2Fslash/complex-has%23hash/has%20space';
Backbone.history.navigate(route, {trigger: true});
strictEqual(router.first, 'has/slash');
strictEqual(router.part, 'has#hash');
strictEqual(router.rest, 'has space');
strictEqual(router.first, 'has%2Fslash');
strictEqual(router.part, 'has%23hash');
strictEqual(router.rest, 'has%20space');
});
test("correctly handles URLs with % (#868)", 3, function() {
@@ -371,13 +292,6 @@
equal(lastRoute, 'search');
});
test("#2666 - Hashes with UTF8 in them.", 2, function() {
Backbone.history.navigate('charñ', {trigger: true});
equal(router.charType, 'UTF');
Backbone.history.navigate('char%C3%B1', {trigger: true});
equal(router.charType, 'escaped');
});
test("#1185 - Use pathname when hashChange is not wanted.", 1, function() {
Backbone.history.stop();
location.replace('http://example.com/path/name#hash');
@@ -543,7 +457,7 @@
Backbone.history.stop();
location.replace('http://example.com/root/x/y?a=b');
location.replace = function(url) {
strictEqual(url, '/root/#x/y?a=b');
strictEqual(url, '/root/?a=b#x/y');
};
Backbone.history = _.extend(new Backbone.History, {
location: location,
@@ -560,7 +474,7 @@
test("#1695 - hashChange to pushState with search.", 1, function() {
Backbone.history.stop();
location.replace('http://example.com/root#x/y?a=b');
location.replace('http://example.com/root?a=b#x/y');
Backbone.history = _.extend(new Backbone.History, {
location: location,
history: {
@@ -609,202 +523,10 @@
test("#2062 - Trigger 'route' event on router instance.", 2, function() {
router.on('route', function(name, args) {
strictEqual(name, 'routeEvent');
deepEqual(args, ['x', null]);
deepEqual(args, ['x']);
});
location.replace('http://example.com#route-event/x');
Backbone.history.checkUrl();
});
test("#2255 - Extend routes by making routes a function.", 1, function() {
var RouterBase = Backbone.Router.extend({
routes: function() {
return {
home: "root",
index: "index.html"
};
}
});
var RouterExtended = RouterBase.extend({
routes: function() {
var _super = RouterExtended.__super__.routes;
return _.extend(_super(),
{ show: "show",
search: "search" });
}
});
var router = new RouterExtended();
deepEqual({home: "root", index: "index.html", show: "show", search: "search"}, router.routes);
});
test("#2538 - hashChange to pushState only if both requested.", 0, function() {
Backbone.history.stop();
location.replace('http://example.com/root?a=b#x/y');
Backbone.history = _.extend(new Backbone.History, {
location: location,
history: {
pushState: function(){},
replaceState: function(){ ok(false); }
}
});
Backbone.history.start({
root: 'root',
pushState: true,
hashChange: false
});
});
test('No hash fallback.', 0, function() {
Backbone.history.stop();
Backbone.history = _.extend(new Backbone.History, {
location: location,
history: {
pushState: function(){},
replaceState: function(){}
}
});
var Router = Backbone.Router.extend({
routes: {
hash: function() { ok(false); }
}
});
var router = new Router;
location.replace('http://example.com/');
Backbone.history.start({
pushState: true,
hashChange: false
});
location.replace('http://example.com/nomatch#hash');
Backbone.history.checkUrl();
});
test('#2656 - No trailing slash on root.', 1, function() {
Backbone.history.stop();
Backbone.history = _.extend(new Backbone.History, {
location: location,
history: {
pushState: function(state, title, url){
strictEqual(url, '/root');
}
}
});
location.replace('http://example.com/root/path');
Backbone.history.start({pushState: true, hashChange: false, root: 'root'});
Backbone.history.navigate('');
});
test('#2656 - No trailing slash on root.', 1, function() {
Backbone.history.stop();
Backbone.history = _.extend(new Backbone.History, {
location: location,
history: {
pushState: function(state, title, url) {
strictEqual(url, '/');
}
}
});
location.replace('http://example.com/path');
Backbone.history.start({pushState: true, hashChange: false});
Backbone.history.navigate('');
});
test('#2765 - Fragment matching sans query/hash.', 2, function() {
Backbone.history.stop();
Backbone.history = _.extend(new Backbone.History, {
location: location,
history: {
pushState: function(state, title, url) {
strictEqual(url, '/path?query#hash');
}
}
});
var Router = Backbone.Router.extend({
routes: {
path: function() { ok(true); }
}
});
var router = new Router;
location.replace('http://example.com/');
Backbone.history.start({pushState: true, hashChange: false});
Backbone.history.navigate('path?query#hash', true);
});
test('Do not decode the search params.', function() {
var Router = Backbone.Router.extend({
routes: {
path: function(params){
strictEqual(params, 'x=y%20z');
}
}
});
var router = new Router;
Backbone.history.navigate('path?x=y%20z', true);
});
test('Navigate to a hash url.', function() {
Backbone.history.stop();
Backbone.history = _.extend(new Backbone.History, {location: location});
Backbone.history.start({pushState: true});
var Router = Backbone.Router.extend({
routes: {
path: function(params) {
strictEqual(params, 'x=y');
}
}
});
var router = new Router;
location.replace('http://example.com/path?x=y#hash');
Backbone.history.checkUrl();
});
test('#navigate to a hash url.', function() {
Backbone.history.stop();
Backbone.history = _.extend(new Backbone.History, {location: location});
Backbone.history.start({pushState: true});
var Router = Backbone.Router.extend({
routes: {
path: function(params) {
strictEqual(params, 'x=y');
}
}
});
var router = new Router;
Backbone.history.navigate('path?x=y#hash', true);
});
test('unicode pathname', 1, function() {
location.replace('http://example.com/myyjä');
Backbone.history.stop();
Backbone.history = _.extend(new Backbone.History, {location: location});
var Router = Backbone.Router.extend({
routes: {
myyjä: function() {
ok(true);
}
}
});
new Router;
Backbone.history.start({pushState: true});
});
test('newline in route', 1, function() {
location.replace('http://example.com/stuff%0Anonsense?param=foo%0Abar');
Backbone.history.stop();
Backbone.history = _.extend(new Backbone.History, {location: location});
var Router = Backbone.Router.extend({
routes: {
'stuff\nnonsense': function() {
ok(true);
}
}
});
new Router;
Backbone.history.start({pushState: true});
});
})();
});

View File

@@ -1,4 +1,4 @@
(function() {
$(document).ready(function() {
var Library = Backbone.Collection.extend({
url : function() { return '/library'; }
@@ -11,18 +11,20 @@
length : 123
};
module("Backbone.sync", {
module("Backbone.sync", _.extend(new Environment, {
setup : function() {
Environment.prototype.setup.apply(this, arguments);
library = new Library;
library.create(attrs, {wait: false});
},
teardown: function() {
Environment.prototype.teardown.apply(this, arguments);
Backbone.emulateHTTP = false;
}
});
}));
test("read", 4, function() {
library.fetch();
@@ -207,4 +209,4 @@
strictEqual(this.ajaxSettings.beforeSend(xhr), false);
});
})();
});

View File

@@ -1,4 +1,4 @@
(function() {
$(document).ready(function() {
var view;
@@ -14,10 +14,13 @@
});
test("constructor", 3, function() {
test("constructor", 6, function() {
equal(view.el.id, 'test-view');
equal(view.el.className, 'test-view');
equal(view.el.other, void 0);
equal(view.options.id, 'test-view');
equal(view.options.className, 'test-view');
equal(view.options.other, 'non-special-option');
});
test("jQuery", 1, function() {
@@ -39,23 +42,23 @@
test("delegateEvents", 6, function() {
var counter1 = 0, counter2 = 0;
var view = new Backbone.View({el: '#testElement'});
var view = new Backbone.View({el: '<p><a id="test"></a></p>'});
view.increment = function(){ counter1++; };
view.$el.on('click', function(){ counter2++; });
var events = {'click h1': 'increment'};
var events = {'click #test': 'increment'};
view.delegateEvents(events);
view.$('h1').trigger('click');
view.$('#test').trigger('click');
equal(counter1, 1);
equal(counter2, 1);
view.$('h1').trigger('click');
view.$('#test').trigger('click');
equal(counter1, 2);
equal(counter2, 2);
view.delegateEvents(events);
view.$('h1').trigger('click');
view.$('#test').trigger('click');
equal(counter1, 3);
equal(counter2, 3);
});
@@ -82,34 +85,27 @@
equal(view.counter, 3);
});
test("delegateEvents ignore undefined methods", 0, function() {
var view = new Backbone.View({el: '<p></p>'});
view.delegateEvents({'click': 'undefinedMethod'});
view.$el.trigger('click');
});
test("undelegateEvents", 6, function() {
var counter1 = 0, counter2 = 0;
var view = new Backbone.View({el: '#testElement'});
var view = new Backbone.View({el: '<p><a id="test"></a></p>'});
view.increment = function(){ counter1++; };
view.$el.on('click', function(){ counter2++; });
var events = {'click h1': 'increment'};
var events = {'click #test': 'increment'};
view.delegateEvents(events);
view.$('h1').trigger('click');
view.$('#test').trigger('click');
equal(counter1, 1);
equal(counter2, 1);
view.undelegateEvents();
view.$('h1').trigger('click');
view.$('#test').trigger('click');
equal(counter1, 1);
equal(counter2, 2);
view.delegateEvents(events);
view.$('h1').trigger('click');
view.$('#test').trigger('click');
equal(counter1, 2);
equal(counter2, 3);
});
@@ -153,6 +149,30 @@
strictEqual(new View().el.id, 'id');
});
test("with options function", 3, function() {
var View1 = Backbone.View.extend({
options: function() {
return {
title: 'title1',
acceptText: 'confirm'
};
}
});
var View2 = View1.extend({
options: function() {
return _.extend(View1.prototype.options.call(this), {
title: 'title2',
fixed: true
});
}
});
strictEqual(new View2().options.title, 'title2');
strictEqual(new View2().options.acceptText, 'confirm');
strictEqual(new View2().options.fixed, true);
});
test("with attributes", 2, function() {
var View = Backbone.View.extend({
attributes: {
@@ -218,7 +238,7 @@
$('body').trigger('fake$event').trigger('fake$event');
equal(count, 2);
$('body').off('.namespaced');
$('body').unbind('.namespaced');
$('body').trigger('fake$event');
equal(count, 2);
});
@@ -292,7 +312,7 @@
view.collection.trigger('x');
});
test("Provide function for el.", 2, function() {
test("Provide function for el.", 1, function() {
var View = Backbone.View.extend({
el: function() {
return "<p><a></a></p>";
@@ -300,28 +320,31 @@
});
var view = new View;
ok(view.$el.is('p'));
ok(view.$el.has('a'));
ok(view.$el.is('p:has(a)'));
});
test("events passed in options", 1, function() {
test("events passed in options", 2, function() {
var counter = 0;
var View = Backbone.View.extend({
el: '#testElement',
el: '<p><a id="test"></a></p>',
increment: function() {
counter++;
}
});
var view = new View({
events: {
'click h1': 'increment'
}
});
var view = new View({events:{'click #test':'increment'}});
var view2 = new View({events:function(){
return {'click #test':'increment'};
}});
view.$('h1').trigger('click').trigger('click');
view.$('#test').trigger('click');
view2.$('#test').trigger('click');
equal(counter, 2);
view.$('#test').trigger('click');
view2.$('#test').trigger('click');
equal(counter, 4);
});
})();
});

View File

@@ -1,4 +1,4 @@
Copyright 2010-2015 Mathias Bynens <http://mathiasbynens.be/>
Copyright 2010-2013 Mathias Bynens <http://mathiasbynens.be/>
Based on JSLitmus.js, copyright Robert Kieffer <http://broofa.com/>
Modified by John-David Dalton <http://allyoucanleet.com/>
@@ -19,4 +19,4 @@ 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.
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

136
vendor/benchmark.js/README.md vendored Normal file
View File

@@ -0,0 +1,136 @@
# Benchmark.js <sup>v1.0.0</sup>
[![build status](https://secure.travis-ci.org/bestiejs/benchmark.js.png)](http://travis-ci.org/bestiejs/benchmark.js)
A [robust](http://calendar.perfplanet.com/2010/bulletproof-javascript-benchmarks/ "Bulletproof JavaScript benchmarks") benchmarking library that works on nearly all JavaScript platforms<sup><a name="fnref1" href="#fn1">1</a></sup>, supports high-resolution timers, and returns statistically significant results. As seen on [jsPerf](http://jsperf.com/).
## Download
* [Development source](https://raw.github.com/bestiejs/benchmark.js/v1.0.0/benchmark.js)
## Dive in
Weve got [API docs](http://benchmarkjs.com/docs) and [unit tests](http://benchmarkjs.com/tests).
For a list of upcoming features, check out our [roadmap](https://github.com/bestiejs/benchmark.js/wiki/Roadmap).
## Support
Benchmark.js has been tested in at least Adobe AIR 3.1, Chrome 5-21, Firefox 1-15, IE 6-9, Opera 9.25-12, Safari 3-6, Node.js 0.8.8, Narwhal 0.3.2, RingoJS 0.8, and Rhino 1.7RC5.
## Installation and usage
In a browser or Adobe AIR:
```html
<script src="benchmark.js"></script>
```
Optionally, expose Javas nanosecond timer by adding the `nano` applet to the `<body>`:
```html
<applet code="nano" archive="nano.jar"></applet>
```
Or enable Chromes microsecond timer by using the [command line switch](http://peter.sh/experiments/chromium-command-line-switches/#enable-benchmarking):
--enable-benchmarking
Via [npm](http://npmjs.org/):
```bash
npm install benchmark
```
In [Node.js](http://nodejs.org/) and [RingoJS v0.8.0+](http://ringojs.org/):
```js
var Benchmark = require('benchmark');
```
Optionally, use the [microtime module](https://github.com/wadey/node-microtime) by Wade Simmons:
```bash
npm install microtime
```
In [RingoJS v0.7.0-](http://ringojs.org/):
```js
var Benchmark = require('benchmark').Benchmark;
```
In [Rhino](http://www.mozilla.org/rhino/):
```js
load('benchmark.js');
```
In an AMD loader like [RequireJS](http://requirejs.org/):
```js
require({
'paths': {
'benchmark': 'path/to/benchmark'
}
},
['benchmark'], function(Benchmark) {
console.log(Benchmark.version);
});
// or with platform.js
// https://github.com/bestiejs/platform.js
require({
'paths': {
'benchmark': 'path/to/benchmark',
'platform': 'path/to/platform'
}
},
['benchmark', 'platform'], function(Benchmark, platform) {
Benchmark.platform = platform;
console.log(Benchmark.platform.name);
});
```
Usage example:
```js
var suite = new Benchmark.Suite;
// add tests
suite.add('RegExp#test', function() {
/o/.test('Hello World!');
})
.add('String#indexOf', function() {
'Hello World!'.indexOf('o') > -1;
})
// add listeners
.on('cycle', function(event) {
console.log(String(event.target));
})
.on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').pluck('name'));
})
// run async
.run({ 'async': true });
// logs:
// > RegExp#test x 4,161,532 +-0.99% (59 cycles)
// > String#indexOf x 6,139,623 +-1.00% (131 cycles)
// > Fastest is String#indexOf
```
## BestieJS
Benchmark.js is part of the BestieJS *"Best in Class"* module collection. This means we promote solid browser/environment support, ES5 precedents, unit testing, and plenty of documentation.
## Authors
* [Mathias Bynens](http://mathiasbynens.be/)
[![twitter/mathias](http://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter")
* [John-David Dalton](http://allyoucanleet.com/)
[![twitter/jdalton](http://gravatar.com/avatar/299a3d891ff1920b69c364d061007043?s=70)](https://twitter.com/jdalton "Follow @jdalton on Twitter")
## Contributors
* [Kit Cambridge](http://kitcambridge.github.com/)
[![twitter/kitcambridge](http://gravatar.com/avatar/6662a1d02f351b5ef2f8b4d815804661?s=70)](https://twitter.com/kitcambridge "Follow @kitcambridge on Twitter")

File diff suppressed because it is too large Load Diff

20
vendor/docdown/LICENSE.txt vendored Normal file
View File

@@ -0,0 +1,20 @@
Copyright 2011-2013 John-David Dalton <http://allyoucanleet.com/>
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.

33
vendor/docdown/README.md vendored Normal file
View File

@@ -0,0 +1,33 @@
# Docdown <sup>v1.0.0</sup>
A simple JSDoc to Markdown documentation generator.
## Documentation
The documentation for Docdown can be viewed here: [/doc/README.md](https://github.com/jdalton/docdown/blob/master/doc/README.md#readme)
For a list of upcoming features, check out our [roadmap](https://github.com/jdalton/docdown/wiki/Roadmap).
## Installation and usage
Usage example:
```php
require("docdown.php");
// generate Markdown
$markdown = docdown(array(
"path" => $filepath,
"url" => "https://github.com/username/project/blob/master/my.js"
));
```
## Author
* [John-David Dalton](http://allyoucanleet.com/)
[![twitter/jdalton](http://gravatar.com/avatar/299a3d891ff1920b69c364d061007043?s=70)](https://twitter.com/jdalton "Follow @jdalton on Twitter")
## Contributors
* [Mathias Bynens](http://mathiasbynens.be/)
[![twitter/mathias](http://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter")

38
vendor/docdown/docdown.php vendored Normal file
View File

@@ -0,0 +1,38 @@
<?php
/*!
* Docdown v1.0.0-pre
* Copyright 2011-2013 John-David Dalton <http://allyoucanleet.com/>
* Available under MIT license <http://mths.be/mit>
*/
require(dirname(__FILE__) . '/src/DocDown/Generator.php');
/**
* Generates Markdown from JSDoc entries in a given file.
*
* @param {Array} [$options=array()] The options array.
* @returns {String} The generated Markdown.
* @example
*
* // specify a file path
* $markdown = docdown(array(
* // path to js file
* 'path' => $filepath,
* // url used to reference line numbers in code
* 'url' => 'https://github.com/username/project/blob/master/my.js'
* ));
*
* // or pass raw js
* $markdown = docdown(array(
* // raw JavaScript source
* 'source' => $rawJS,
* // documentation title
* 'title' => 'My API Documentation',
* // url used to reference line numbers in code
* 'url' => 'https://github.com/username/project/blob/master/my.js'
* ));
*/
function docdown( $options = array() ) {
$gen = new Generator($options);
return $gen->generate();
}
?>

226
vendor/docdown/src/DocDown/Alias.php vendored Normal file
View File

@@ -0,0 +1,226 @@
<?php
/**
* A class to represent a JSDoc entry alias.
*/
class Alias {
/**
* The alias owner.
*
* @memberOf Alias
* @type Object
*/
public $owner;
/*--------------------------------------------------------------------------*/
/**
* The Alias constructor.
*
* @constructor
* @param {String} $name The alias name.
* @param {Object} $owner The alias owner.
*/
public function __construct( $name, $owner ) {
$this->owner = $owner;
$this->_name = $name;
$this->_call = $owner->getCall();
$this->_category = $owner->getCategory();
$this->_desc = $owner->getDesc();
$this->_example = $owner->getExample();
$this->_isCtor = $owner->isCtor();
$this->_isLicense = $owner->isLicense();
$this->_isPlugin = $owner->isPlugin();
$this->_isPrivate = $owner->isPrivate();
$this->_isStatic = $owner->isStatic();
$this->_lineNumber = $owner->getLineNumber();
$this->_members = $owner->getMembers();
$this->_params = $owner->getParams();
$this->_returns = $owner->getReturns();
$this->_type = $owner->getType();
}
/*--------------------------------------------------------------------------*/
/**
* Extracts the entry's `alias` objects.
*
* @memberOf Alias
* @param {Number} $index The index of the array value to return.
* @returns {Array|String} The entry's `alias` objects.
*/
public function getAliases( $index = null ) {
$result = array();
return $index !== null
? @$result[$index]
: $result;
}
/**
* Extracts the function call from the owner entry.
*
* @memberOf Alias
* @returns {String} The function call.
*/
public function getCall() {
return $this->_call;
}
/**
* Extracts the owner entry's `category` data.
*
* @memberOf Alias
* @returns {String} The owner entry's `category` data.
*/
public function getCategory() {
return $this->_category;
}
/**
* Extracts the owner entry's description.
*
* @memberOf Alias
* @returns {String} The owner entry's description.
*/
public function getDesc() {
return $this->_desc;
}
/**
* Extracts the owner entry's `example` data.
*
* @memberOf Alias
* @returns {String} The owner entry's `example` data.
*/
public function getExample() {
return $this->_example;
}
/**
* Checks if the entry is an alias.
*
* @memberOf Alias
* @returns {Boolean} Returns `true`.
*/
public function isAlias() {
return true;
}
/**
* Checks if the owner entry is a constructor.
*
* @memberOf Alias
* @returns {Boolean} Returns `true` if a constructor, else `false`.
*/
public function isCtor() {
return $this->_isCtor;
}
/**
* Checks if the owner entry is a license.
*
* @memberOf Alias
* @returns {Boolean} Returns `true` if a license, else `false`.
*/
public function isLicense() {
return $this->_isLicense;
}
/**
* Checks if the owner entry *is* assigned to a prototype.
*
* @memberOf Alias
* @returns {Boolean} Returns `true` if assigned to a prototype, else `false`.
*/
public function isPlugin() {
return $this->_isPlugin;
}
/**
* Checks if the owner entry is private.
*
* @memberOf Alias
* @returns {Boolean} Returns `true` if private, else `false`.
*/
public function isPrivate() {
return $this->_isPrivate;
}
/**
* Checks if the owner entry is *not* assigned to a prototype.
*
* @memberOf Alias
* @returns {Boolean} Returns `true` if not assigned to a prototype, else `false`.
*/
public function isStatic() {
return $this->_isStatic;
}
/**
* Resolves the owner entry's line number.
*
* @memberOf Alias
* @returns {Number} The owner entry's line number.
*/
public function getLineNumber() {
return $this->_lineNumber;
}
/**
* Extracts the owner entry's `member` data.
*
* @memberOf Alias
* @param {Number} $index The index of the array value to return.
* @returns {Array|String} The owner entry's `member` data.
*/
public function getMembers( $index = null ) {
return $index !== null
? @$this->_members[$index]
: $this->_members;
}
/**
* Extracts the owner entry's `name` data.
*
* @memberOf Alias
* @returns {String} The owner entry's `name` data.
*/
public function getName() {
return $this->_name;
}
/**
* Extracts the owner entry's `param` data.
*
* @memberOf Alias
* @param {Number} $index The index of the array value to return.
* @returns {Array} The owner entry's `param` data.
*/
public function getParams( $index = null ) {
return $index !== null
? @$this->_params[$index]
: $this->_params;
}
/**
* Extracts the owner entry's `returns` data.
*
* @memberOf Alias
* @returns {String} The owner entry's `returns` data.
*/
public function getReturns() {
return $this->_returns;
}
/**
* Extracts the owner entry's `type` data.
*
* @memberOf Alias
* @returns {String} The owner entry's `type` data.
*/
public function getType() {
return $this->_type;
}
}
?>

442
vendor/docdown/src/DocDown/Entry.php vendored Normal file
View File

@@ -0,0 +1,442 @@
<?php
require(dirname(__FILE__) . "/Alias.php");
/**
* A class to simplify parsing a single JSDoc entry.
*/
class Entry {
/**
* The documentation entry.
*
* @memberOf Entry
* @type String
*/
public $entry = '';
/**
* The language highlighter used for code examples.
*
* @memberOf Entry
* @type String
*/
public $lang = '';
/**
* The source code.
*
* @memberOf Entry
* @type String
*/
public $source = '';
/*--------------------------------------------------------------------------*/
/**
* The Entry constructor.
*
* @constructor
* @param {String} $entry The documentation entry to analyse.
* @param {String} $source The source code.
* @param {String} [$lang ='js'] The language highlighter used for code examples.
*/
public function __construct( $entry, $source, $lang = 'js' ) {
$this->entry = $entry;
$this->lang = $lang;
$this->source = str_replace(PHP_EOL, "\n", $source);
}
/*--------------------------------------------------------------------------*/
/**
* Extracts the documentation entries from source code.
*
* @static
* @memberOf Entry
* @param {String} $source The source code.
* @returns {Array} The array of entries.
*/
public static function getEntries( $source ) {
preg_match_all('#/\*\*(?![-!])[\s\S]*?\*/\s*[^\n]+#', $source, $result);
return array_pop($result);
}
/*--------------------------------------------------------------------------*/
/**
* Checks if the entry is a function reference.
*
* @private
* @memberOf Entry
* @returns {Boolean} Returns `true` if the entry is a function reference, else `false`.
*/
private function isFunction() {
if (!isset($this->_isFunction)) {
$this->_isFunction = !!(
$this->isCtor() ||
count($this->getParams()) ||
count($this->getReturns()) ||
preg_match('/\* *@function\b/', $this->entry)
);
}
return $this->_isFunction;
}
/*--------------------------------------------------------------------------*/
/**
* Extracts the entry's `alias` objects.
*
* @memberOf Entry
* @param {Number} $index The index of the array value to return.
* @returns {Array|String} The entry's `alias` objects.
*/
public function getAliases( $index = null ) {
if (!isset($this->_aliases)) {
preg_match('#\* *@alias\s+([^\n]+)#', $this->entry, $result);
if (count($result)) {
$result = trim(preg_replace('/(?:^|\n)\s*\* ?/', ' ', $result[1]));
$result = preg_split('/,\s*/', $result);
natsort($result);
foreach ($result as $resultIndex => $value) {
$result[$resultIndex] = new Alias($value, $this);
}
}
$this->_aliases = $result;
}
return $index !== null
? @$this->_aliases[$index]
: $this->_aliases;
}
/**
* Extracts the function call from the entry.
*
* @memberOf Entry
* @returns {String} The function call.
*/
public function getCall() {
if (isset($this->_call)) {
return $this->_call;
}
preg_match('#\*/\s*(?:function ([^(]*)|(.*?)(?=[:=,]|return\b))#', $this->entry, $result);
if ($result = array_pop($result)) {
$result = array_pop(explode('var ', trim(trim(array_pop(explode('.', $result))), "'")));
}
// resolve name
// avoid $this->getName() because it calls $this->getCall()
preg_match('#\* *@name\s+([^\n]+)#', $this->entry, $name);
if (count($name)) {
$name = trim($name[1]);
} else {
$name = $result;
}
// compile function call syntax
if ($this->isFunction()) {
// compose parts
$result = array($result);
$params = $this->getParams();
foreach ($params as $param) {
$result[] = $param[1];
}
// format
$result = $name .'('. implode(array_slice($result, 1), ', ') .')';
$result = str_replace(', [', ' [, ', str_replace('], [', ', ', $result));
}
$this->_call = $result ? $result : $name;
return $this->_call;
}
/**
* Extracts the entry's `category` data.
*
* @memberOf Entry
* @returns {String} The entry's `category` data.
*/
public function getCategory() {
if (isset($this->_category)) {
return $this->_category;
}
preg_match('#\* *@category\s+([^\n]+)#', $this->entry, $result);
if (count($result)) {
$result = trim(preg_replace('/(?:^|\n)\s*\* ?/', ' ', $result[1]));
} else {
$result = $this->getType() == 'Function' ? 'Methods' : 'Properties';
}
$this->_category = $result;
return $result;
}
/**
* Extracts the entry's description.
*
* @memberOf Entry
* @returns {String} The entry's description.
*/
public function getDesc() {
if (isset($this->_desc)) {
return $this->_desc;
}
preg_match('#/\*\*(?:\s*\*)?([\s\S]*?)(?=\*\s\@[a-z]|\*/)#', $this->entry, $result);
if (count($result)) {
$type = $this->getType();
$result = preg_replace('/:\n *\* */', ":<br>\n", $result[1]);
$result = preg_replace('/(?:^|\n) *\*\n *\* */', "\n\n", $result);
$result = preg_replace('/(?:^|\n) *\* ?/', ' ', $result);
$result = trim($result);
$result = ($type == 'Function' ? '' : '(' . str_replace('|', ', ', trim($type, '{}')) . '): ') . $result;
}
$this->_desc = $result;
return $result;
}
/**
* Extracts the entry's `example` data.
*
* @memberOf Entry
* @returns {String} The entry's `example` data.
*/
public function getExample() {
if (isset($this->_example)) {
return $this->_example;
}
preg_match('#\* *@example\s+([\s\S]*?)(?=\*\s\@[a-z]|\*/)#', $this->entry, $result);
if (count($result)) {
$result = trim(preg_replace('/(?:^|\n)\s*\* ?/', "\n", $result[1]));
$result = '```' . $this->lang . "\n" . $result . "\n```";
}
$this->_example = $result;
return $result;
}
/**
* Checks if the entry is an alias.
*
* @memberOf Entry
* @returns {Boolean} Returns `false`.
*/
public function isAlias() {
return false;
}
/**
* Checks if the entry is a constructor.
*
* @memberOf Entry
* @returns {Boolean} Returns `true` if a constructor, else `false`.
*/
public function isCtor() {
if (!isset($this->_isCtor)) {
$this->_isCtor = !!preg_match('/\* *@constructor\b/', $this->entry);
}
return $this->_isCtor;
}
/**
* Checks if the entry is a license.
*
* @memberOf Entry
* @returns {Boolean} Returns `true` if a license, else `false`.
*/
public function isLicense() {
if (!isset($this->_isLicense)) {
$this->_isLicense = !!preg_match('/\* *@license\b/', $this->entry);
}
return $this->_isLicense;
}
/**
* Checks if the entry *is* assigned to a prototype.
*
* @memberOf Entry
* @returns {Boolean} Returns `true` if assigned to a prototype, else `false`.
*/
public function isPlugin() {
if (!isset($this->_isPlugin)) {
$this->_isPlugin = !$this->isCtor() && !$this->isPrivate() && !$this->isStatic();
}
return $this->_isPlugin;
}
/**
* Checks if the entry is private.
*
* @memberOf Entry
* @returns {Boolean} Returns `true` if private, else `false`.
*/
public function isPrivate() {
if (!isset($this->_isPrivate)) {
$this->_isPrivate = $this->isLicense() || !!preg_match('/\* *@private\b/', $this->entry) || !preg_match('/\* *@[a-z]+\b/', $this->entry);
}
return $this->_isPrivate;
}
/**
* Checks if the entry is *not* assigned to a prototype.
*
* @memberOf Entry
* @returns {Boolean} Returns `true` if not assigned to a prototype, else `false`.
*/
public function isStatic() {
if (isset($this->_isStatic)) {
return $this->_isStatic;
}
$public = !$this->isPrivate();
$result = $public && !!preg_match('/\* *@static\b/', $this->entry);
// set in cases where it isn't explicitly stated
if ($public && !$result) {
if ($parent = array_pop(preg_split('/[#.]/', $this->getMembers(0)))) {
foreach (Entry::getEntries($this->source) as $entry) {
$entry = new Entry($entry, $this->source);
if ($entry->getName() == $parent) {
$result = !$entry->isCtor();
break;
}
}
} else {
$result = true;
}
}
$this->_isStatic = $result;
return $result;
}
/**
* Resolves the entry's line number.
*
* @memberOf Entry
* @returns {Number} The entry's line number.
*/
public function getLineNumber() {
if (!isset($this->_lineNumber)) {
preg_match_all('/\n/', substr($this->source, 0, strrpos($this->source, $this->entry) + strlen($this->entry)), $lines);
$this->_lineNumber = count(array_pop($lines)) + 1;
}
return $this->_lineNumber;
}
/**
* Extracts the entry's `member` data.
*
* @memberOf Entry
* @param {Number} $index The index of the array value to return.
* @returns {Array|String} The entry's `member` data.
*/
public function getMembers( $index = null ) {
if (!isset($this->_members)) {
preg_match('#\* *@member(?:Of)?\s+([^\n]+)#', $this->entry, $result);
if (count($result)) {
$result = trim(preg_replace('/(?:^|\n)\s*\* ?/', ' ', $result[1]));
$result = preg_split('/,\s*/', $result);
natsort($result);
}
$this->_members = $result;
}
return $index !== null
? @$this->_members[$index]
: $this->_members;
}
/**
* Extracts the entry's `name` data.
*
* @memberOf Entry
* @returns {String} The entry's `name` data.
*/
public function getName() {
if (isset($this->_name)) {
return $this->_name;
}
preg_match('#\* *@name\s+([^\n]+)#', $this->entry, $result);
if (count($result)) {
$result = trim(preg_replace('/(?:^|\n)\s*\* ?/', ' ', $result[1]));
} else {
$result = array_shift(explode('(', $this->getCall()));
}
$this->_name = $result;
return $result;
}
/**
* Extracts the entry's `param` data.
*
* @memberOf Entry
* @param {Number} $index The index of the array value to return.
* @returns {Array} The entry's `param` data.
*/
public function getParams( $index = null ) {
if (!isset($this->_params)) {
preg_match_all('#\* *@param\s+\{([^}]+)\}\s+(\[.+\]|[$\w|]+(?:\[.+\])?)\s+([\s\S]*?)(?=\*\s\@[a-z]|\*/)#i', $this->entry, $result);
if (count($result = array_filter(array_slice($result, 1)))) {
// repurpose array
foreach ($result as $param) {
foreach ($param as $key => $value) {
if (!is_array($result[0][$key])) {
$result[0][$key] = array();
}
$result[0][$key][] = trim(preg_replace('/(?:^|\n)\s*\* */', ' ', $value));
}
}
$result = $result[0];
}
$this->_params = $result;
}
return $index !== null
? @$this->_params[$index]
: $this->_params;
}
/**
* Extracts the entry's `returns` data.
*
* @memberOf Entry
* @returns {String} The entry's `returns` data.
*/
public function getReturns() {
if (isset($this->_returns)) {
return $this->_returns;
}
preg_match('#\* *@returns\s+\{([^}]+)\}\s+([\s\S]*?)(?=\*\s\@[a-z]|\*/)#', $this->entry, $result);
if (count($result)) {
$result = array_map('trim', array_slice($result, 1));
$result[0] = str_replace('|', ', ', $result[0]);
$result[1] = preg_replace('/(?:^|\n)\s*\* ?/', ' ', $result[1]);
}
$this->_returns = $result;
return $result;
}
/**
* Extracts the entry's `type` data.
*
* @memberOf Entry
* @returns {String} The entry's `type` data.
*/
public function getType() {
if (isset($this->_type)) {
return $this->_type;
}
preg_match('#\* *@type\s+([^\n]+)#', $this->entry, $result);
if (count($result)) {
$result = trim(preg_replace('/(?:^|\n)\s*\* ?/', ' ', $result[1]));
} else {
$result = $this->isFunction() ? 'Function' : 'Unknown';
}
$this->_type = $result;
return $result;
}
}
?>

565
vendor/docdown/src/DocDown/Generator.php vendored Normal file
View File

@@ -0,0 +1,565 @@
<?php
require(dirname(__FILE__) . "/Entry.php");
/**
* Generates Markdown from JSDoc entries.
*/
class Generator {
/**
* The HTML for the close tag.
*
* @static
* @memberOf Generator
* @type String
*/
public $closeTag = "\n<!-- /div -->\n";
/**
* An array of JSDoc entries.
*
* @memberOf Generator
* @type Array
*/
public $entries = array();
/**
* The HTML for the open tag.
*
* @static
* @memberOf Generator
* @type String
*/
public $openTag = "\n<!-- div -->\n";
/**
* An options array used to configure the generator.
*
* @memberOf Generator
* @type Array
*/
public $options = array();
/**
* The file's source code.
*
* @memberOf Generator
* @type String
*/
public $source = '';
/*--------------------------------------------------------------------------*/
/**
* The Generator constructor.
*
* @constructor
* @param {String} $source The source code to parse.
* @param {Array} $options The options array.
*/
public function __construct( $source, $options = array() ) {
// juggle arguments
if (is_array($source)) {
$options = $source;
} else {
$options['source'] = $source;
}
if (isset($options['source']) && realpath($options['source'])) {
$options['path'] = $options['source'];
}
if (isset($options['path'])) {
preg_match('/(?<=\.)[a-z]+$/', $options['path'], $ext);
$options['source'] = file_get_contents($options['path']);
$ext = array_pop($ext);
if (!isset($options['lang']) && $ext) {
$options['lang'] = $ext;
}
if (!isset($options['title'])) {
$options['title'] = ucfirst(basename($options['path'])) . ' API documentation';
}
}
if (!isset($options['lang'])) {
$options['lang'] = 'js';
}
if (!isset($options['toc'])) {
$options['toc'] = 'properties';
}
$this->options = $options;
$this->source = str_replace(PHP_EOL, "\n", $options['source']);
$this->entries = Entry::getEntries($this->source);
foreach ($this->entries as $index => $value) {
$this->entries[$index] = new Entry($value, $this->source, $options['lang']);
}
}
/*--------------------------------------------------------------------------*/
/**
* Performs common string formatting operations.
*
* @private
* @static
* @memberOf Generator
* @param {String} $string The string to format.
* @returns {String} The formatted string.
*/
private static function format( $string ) {
$counter = 0;
// tokenize inline code snippets
preg_match_all('/`[^`]+`/', $string, $tokenized);
$tokenized = $tokenized[0];
foreach ($tokenized as $snippet) {
$string = str_replace($snippet, '__token' . ($counter++) .'__', $string);
}
// italicize parentheses
$string = preg_replace('/(^|\s)(\([^)]+\))/', '$1*$2*', $string);
// mark numbers as inline code
$string = preg_replace('/ (-?\d+(?:.\d+)?)(?!\.[^\n])/', ' `$1`', $string);
// detokenize inline code snippets
$counter = 0;
foreach ($tokenized as $snippet) {
$string = str_replace('__token' . ($counter++) . '__', $snippet, $string);
}
return trim($string);
}
/**
* Modify a string by replacing named tokens with matching assoc. array values.
*
* @private
* @static
* @memberOf Generator
* @param {String} $string The string to modify.
* @param {Array|Object} $object The template object.
* @returns {String} The modified string.
*/
private static function interpolate( $string, $object ) {
preg_match_all('/#\{([^}]+)\}/', $string, $tokens);
$tokens = array_unique(array_pop($tokens));
foreach ($tokens as $token) {
$pattern = '/#\{' . $token . '\}/';
$replacement = '';
if (is_object($object)) {
preg_match('/\(([^)]+?)\)$/', $token, $args);
$args = preg_split('/,\s*/', array_pop($args));
$method = 'get' . ucfirst(str_replace('/\([^)]+?\)$/', '', $token));
if (method_exists($object, $method)) {
$replacement = (string) call_user_func_array(array($object, $method), $args);
} else if (isset($object->{$token})) {
$replacement = (string) $object->{$token};
}
} else if (isset($object[$token])) {
$replacement = (string) $object[$token];
}
$string = preg_replace($pattern, trim($replacement), $string);
}
return Generator::format($string);
}
/*--------------------------------------------------------------------------*/
/**
* Adds the given `$entries` to the `$result` array.
*
* @private
* @memberOf Generator
* @param {Array} $result The result array to modify.
* @param {Array} $entries The entries to add to the `$result`.
*/
private function addEntries( &$result, $entries ) {
foreach ($entries as $entry) {
// skip aliases
if ($entry->isAlias()) {
continue;
}
// name and description
array_push(
$result,
$this->openTag,
Generator::interpolate("### <a id=\"#{hash}\"></a>`#{member}#{separator}#{call}`\n<a href=\"##{hash}\">#</a> [&#x24C8;](#{href} \"View in source\") [&#x24C9;][1]\n\n#{desc}", $entry)
);
// @alias
if (count($aliases = $entry->getAliases())) {
array_push($result, '', '#### Aliases');
foreach ($aliases as $index => $alias) {
$aliases[$index] = $alias->getName();
}
$result[] = '*' . implode(', ', $aliases) . '*';
}
// @param
if (count($params = $entry->getParams())) {
array_push($result, '', '#### Arguments');
foreach ($params as $index => $param) {
$result[] = Generator::interpolate('#{num}. `#{name}` (#{type}): #{desc}', array(
'desc' => $param[2],
'name' => $param[1],
'num' => $index + 1,
'type' => $param[0]
));
}
}
// @returns
if (count($returns = $entry->getReturns())) {
array_push(
$result, '',
'#### Returns',
Generator::interpolate('(#{type}): #{desc}', array('desc' => $returns[1], 'type' => $returns[0]))
);
}
// @example
if ($example = $entry->getExample()) {
array_push($result, '', '#### Example', $example);
}
array_push($result, "\n* * *", $this->closeTag);
}
}
/**
* Resolves the entry's hash used to navigate the documentation.
*
* @private
* @memberOf Generator
* @param {Number|Object} $entry The entry object.
* @param {String} $member The name of the member.
* @returns {String} The url hash.
*/
private function getHash( $entry, $member = '' ) {
$entry = is_numeric($entry) ? $this->entries[$entry] : $entry;
$member = !$member ? $entry->getMembers(0) : $member;
$result = ($member ? $member . ($entry->isPlugin() ? 'prototype' : '') : '') . $entry->getCall();
$result = preg_replace('/\(\[|\[\]/', '', $result);
$result = preg_replace('/[ =|\'"{}.()\]]/', '', $result);
$result = preg_replace('/[[#,]/', '-', $result);
return strtolower($result);
}
/**
* Resolves the entry's url for the specific line number.
*
* @private
* @memberOf Generator
* @param {Number|Object} $entry The entry object.
* @returns {String} The url.
*/
private function getLineUrl( $entry ) {
$entry = is_numeric($entry) ? $this->entries($entry) : $entry;
return $this->options['url'] . '#L' . $entry->getLineNumber();
}
/**
* Extracts the character used to separate the entry's name from its member.
*
* @private
* @memberOf Generator
* @param {Number|Object} $entry The entry object.
* @returns {String} The separator.
*/
private function getSeparator( $entry ) {
$entry = is_numeric($entry) ? $this->entries($entry) : $entry;
return $entry->isPlugin() ? '.prototype.' : '.';
}
/*--------------------------------------------------------------------------*/
/**
* Generates Markdown from JSDoc entries.
*
* @memberOf Generator
* @returns {String} The rendered Markdown.
*/
public function generate() {
$api = array();
$byCategory = $this->options['toc'] == 'categories';
$categories = array();
$closeTag = $this->closeTag;
$compiling = false;
$openTag = $this->openTag;
$result = array('# ' . $this->options['title']);
$toc = 'toc';
// initialize $api array
foreach ($this->entries as $entry) {
// skip invalid or private entries
$name = $entry->getName();
if (!$name || $entry->isPrivate()) {
continue;
}
$members = $entry->getMembers();
$members = count($members) ? $members : array('');
foreach ($members as $member) {
// create api category arrays
if ($member && !isset($api[$member])) {
// create temporary entry to be replaced later
$api[$member] = new stdClass;
$api[$member]->static = array();
$api[$member]->plugin = array();
}
// append entry to api member
if (!$member || $entry->isCtor() || ($entry->getType() == 'Object' &&
!preg_match('/[=:]\s*(?:null|undefined)\s*[,;]?$/', $entry->entry))) {
// assign the real entry, replacing the temporary entry if it exist
$member = ($member ? $member . ($entry->isPlugin() ? '#' : '.') : '') . $name;
$entry->static = @$api[$member] ? $api[$member]->static : array();
$entry->plugin = @$api[$member] ? $api[$member]->plugin : array();
$api[$member] = $entry;
foreach ($entry->getAliases() as $alias) {
$api[$member] = $alias;
$alias->static = array();
$alias->plugin = array();
}
}
else if ($entry->isStatic()) {
$api[$member]->static[] = $entry;
foreach ($entry->getAliases() as $alias) {
$api[$member]->static[] = $alias;
}
}
else if (!$entry->isCtor()) {
$api[$member]->plugin[] = $entry;
foreach ($entry->getAliases() as $alias) {
$api[$member]->plugin[] = $alias;
}
}
}
}
// add properties to each entry
foreach ($api as $entry) {
$entry->hash = $this->getHash($entry);
$entry->href = $this->getLineUrl($entry);
$member = $entry->getMembers(0);
$member = ($member ? $member . ($entry->isPlugin() ? '.prototype.' : '.') : '') . $entry->getName();
$entry->member = preg_replace('/' . $entry->getName() . '$/', '', $member);
// add properties to static and plugin sub-entries
foreach (array('static', 'plugin') as $kind) {
foreach ($entry->{$kind} as $subentry) {
$subentry->hash = $this->getHash($subentry);
$subentry->href = $this->getLineUrl($subentry);
$subentry->member = $member;
$subentry->separator = $this->getSeparator($subentry);
}
}
}
/*------------------------------------------------------------------------*/
// custom sort for root level entries
// TODO: see how well it handles deeper namespace traversal
function sortCompare($a, $b) {
$score = array( 'a' => 0, 'b' => 0);
foreach (array( 'a' => $a, 'b' => $b) as $key => $value) {
// capitalized properties are last
if (preg_match('/[#.][A-Z]/', $value)) {
$score[$key] = 0;
}
// lowercase prototype properties are next to last
else if (preg_match('/#[a-z]/', $value)) {
$score[$key] = 1;
}
// lowercase static properties next to first
else if (preg_match('/\.[a-z]/', $value)) {
$score[$key] = 2;
}
// root properties are first
else if (preg_match('/^[^#.]+$/', $value)) {
$score[$key] = 3;
}
}
$score = $score['b'] - $score['a'];
return $score ? $score : strcasecmp($a, $b);
}
uksort($api, 'sortCompare');
// sort static and plugin sub-entries
foreach ($api as $entry) {
foreach (array('static', 'plugin') as $kind) {
$sortBy = array( 'a' => array(), 'b' => array(), 'c' => array() );
foreach ($entry->{$kind} as $subentry) {
$name = $subentry->getName();
// functions w/o ALL-CAPs names are last
$sortBy['a'][] = $subentry->getType() == 'Function' && !preg_match('/^[A-Z_]+$/', $name);
// ALL-CAPs properties first
$sortBy['b'][] = preg_match('/^[A-Z_]+$/', $name);
// lowercase alphanumeric sort
$sortBy['c'][] = strtolower($name);
}
array_multisort($sortBy['a'], SORT_ASC, $sortBy['b'], SORT_DESC, $sortBy['c'], SORT_ASC, $entry->{$kind});
}
}
/*------------------------------------------------------------------------*/
// add categories
foreach ($api as $entry) {
$categories[$entry->getCategory()][] = $entry;
foreach (array('static', 'plugin') as $kind) {
foreach ($entry->{$kind} as $subentry) {
$categories[$subentry->getCategory()][] = $subentry;
}
}
}
// sort categories
ksort($categories);
foreach(array('Methods', 'Properties') as $category) {
if (isset($categories[$category])) {
$entries = $categories[$category];
unset($categories[$category]);
$categories[$category] = $entries;
}
}
/*------------------------------------------------------------------------*/
// compile TOC
$result[] = $openTag;
// compile TOC by categories
if ($byCategory) {
foreach ($categories as $category => $entries) {
if ($compiling) {
$result[] = $closeTag;
} else {
$compiling = true;
}
// assign TOC hash
if (count($result) == 2) {
$toc = $category;
}
// add category
array_push(
$result,
$openTag, '## ' . (count($result) == 2 ? '<a id="' . $toc . '"></a>' : '') . '`' . $category . '`'
);
// add entries
foreach ($entries as $entry) {
$result[] = Generator::interpolate('* [`#{member}#{separator}#{name}`](##{hash})', $entry);
}
}
}
// compile TOC by namespace
else {
foreach ($api as $entry) {
if ($compiling) {
$result[] = $closeTag;
} else {
$compiling = true;
}
$member = $entry->member . $entry->getName();
// assign TOC hash
if (count($result) == 2) {
$toc = $member;
}
// add root entry
array_push(
$result,
$openTag, '## ' . (count($result) == 2 ? '<a id="' . $toc . '"></a>' : '') . '`' . $member . '`',
Generator::interpolate('* [`' . $member . '`](##{hash})', $entry)
);
// add static and plugin sub-entries
foreach (array('static', 'plugin') as $kind) {
if ($kind == 'plugin' && count($entry->plugin)) {
array_push(
$result,
$closeTag,
$openTag,
'## `' . $member . ($entry->isCtor() ? '.prototype`' : '`')
);
}
foreach ($entry->{$kind} as $subentry) {
$subentry->member = $member;
$result[] = Generator::interpolate('* [`#{member}#{separator}#{name}`](##{hash})', $subentry);
}
}
}
}
array_push($result, $closeTag, $closeTag);
/*------------------------------------------------------------------------*/
// compile content
$compiling = false;
$result[] = $openTag;
if ($byCategory) {
foreach ($categories as $category => $entries) {
if ($compiling) {
$result[] = $closeTag;
} else {
$compiling = true;
}
if ($category != 'Methods' && $category != 'Properties') {
$category = '“' . $category . '” Methods';
}
array_push($result, $openTag, '## `' . $category . '`');
$this->addEntries($result, $entries);
}
}
else {
foreach ($api as $entry) {
// skip aliases
if ($entry->isAlias()) {
continue;
}
if ($compiling) {
$result[] = $closeTag;
} else {
$compiling = true;
}
// add root entry name
$member = $entry->member . $entry->getName();
array_push($result, $openTag, '## `' . $member . '`');
foreach (array($entry, 'static', 'plugin') as $kind) {
$subentries = is_string($kind) ? $entry->{$kind} : array($kind);
// add sub-entry name
if ($kind != 'static' && $entry->getType() != 'Object' &&
count($subentries) && $subentries[0] != $kind) {
if ($kind == 'plugin') {
$result[] = $closeTag;
}
array_push(
$result,
$openTag,
'## `' . $member . ($kind == 'plugin' ? '.prototype`' : '`')
);
}
$this->addEntries($result, $subentries);
}
}
}
// close tags add TOC link reference
array_push($result, $closeTag, $closeTag, '', ' [1]: #' . $toc . ' "Jump back to the TOC."');
// cleanup whitespace
return trim(preg_replace('/ +\n/', "\n", join($result, "\n")));
}
}
?>

View File

@@ -70,7 +70,7 @@ html, body {
body {
font-family: Lucida Grande, Tahoma, sans-serif;
font-size: 11px;
background: #fff;
background: #fff;
}
.clear {
@@ -103,7 +103,7 @@ body {
border: 1px solid #ccc;
margin: 0 5px 0 0;
background: #fff url(search.png) no-repeat 4px 2px;
padding-left: 20px;
padding-left: 20px;
font-size: 11px;
}
@@ -124,7 +124,7 @@ body {
height: 14px;
background: url(errorIcon.png) no-repeat;
color: #f00;
font-weight: bold;
font-weight: bold;
}
#fbMiniErrors {
@@ -139,7 +139,7 @@ body {
margin: 3px 4px 0;
height: 20px;
width: 20px;
float: right;
float: right;
background: url(sprite.png) 0 -135px;
cursor: pointer;
}
@@ -192,10 +192,10 @@ body {
}
/************************************************************************************************
Sub-Layout
Sub-Layout
*************************************************************************************************/
/* fbToolbar
/* fbToolbar
*************************************************************************************************/
#fbToolbarIcon {
float: left;
@@ -237,7 +237,7 @@ body {
position: relative;
top: 5px;
line-height: 19px;
cursor: default;
cursor: default;
}
.fbToolbarSeparator{
@@ -262,7 +262,7 @@ body {
.fbStatusBar span a:hover {
color: blue;
cursor: pointer;
cursor: pointer;
}
@@ -307,7 +307,7 @@ body {
padding-left: 10px;
}
/* body
/* body
*************************************************************************************************/
.fbPanel {
display: none;
@@ -340,7 +340,7 @@ body {
visibility: hidden !important;
}
/* fbBottom
/* fbBottom
*************************************************************************************************/
#fbCommand {
@@ -391,7 +391,7 @@ div.fbFitHeight {
Layout Controls
*************************************************************************************************/
/* fbToolbar buttons
/* fbToolbar buttons
*************************************************************************************************/
#fbWindowButtons a {
font-size: 1px;
@@ -420,7 +420,7 @@ div.fbFitHeight {
background: url(sprite.png) -48px -119px;
}
/* fbPanelBarBox tabs
/* fbPanelBarBox tabs
*************************************************************************************************/
.fbTab {
text-decoration: none;
@@ -475,7 +475,7 @@ a.fbTab:hover .fbTabR {
background: url(sprite.png) -8px -96px !important;
}
/* splitters
/* splitters
*************************************************************************************************/
#fbHSplitter {
position: absolute;
@@ -571,7 +571,7 @@ div.objectBox-element {
color: #fff !important;
}
/* Webkit CSS Hack - bug in "highlight" named color */
/* Webkit CSS Hack - bug in "highlight" named color */
@media screen and (-webkit-min-device-pixel-ratio:0) {
.selectedElement{
background: #316AC5;

View File

@@ -136,10 +136,10 @@ h1.groupHeader {
position: relative;
top: -7px;
left: -5px;
outline: none;
resize: none;
/*
_border: 1px solid #999 !important;
_padding: 1px !important;
@@ -311,17 +311,17 @@ h1.groupHeader {
outline: none;
background-color: transparent
}
.useA11y .a11yCSSView .focusRow:focus .cssSelector,
.useA11y .a11yCSSView .focusRow:focus .cssPropName,
.useA11y .a11yCSSView .focusRow:focus .cssSelector,
.useA11y .a11yCSSView .focusRow:focus .cssPropName,
.useA11y .a11yCSSView .focusRow:focus .cssPropValue,
.useA11y .a11yCSSView .computedStyleRow:focus,
.useA11y .a11yCSSView .computedStyleRow:focus,
.useA11y .a11yCSSView .groupHeader:focus {
outline: 2px solid #FF9933;
outline-offset: -2px;
background-color: #FFFFD6;
}
.useA11y .a11yCSSView .groupHeader:focus {
outline-offset: -2px;
}
@@ -731,7 +731,7 @@ h1.groupHeader {
/* Time Info tip */
.timeInfoTip {
width: 150px;
width: 150px;
height: 40px
}
@@ -944,7 +944,7 @@ h1.groupHeader {
/*overflow-x: auto; HTML is damaged in case of big (2-3MB) responses */
}
/* replaced by .netInfoTextSelected for IE6 support
/* replaced by .netInfoTextSelected for IE6 support
.netInfoText[selected="true"] {
display: block;
}
@@ -963,7 +963,7 @@ h1.groupHeader {
}
.netInfoPostText .netInfoParamName {
width: 1px; /* Google Chrome need this otherwise the first column of
width: 1px; /* Google Chrome need this otherwise the first column of
the post variables table will be larger than expected */
}
@@ -1148,7 +1148,7 @@ h1.groupHeader {
}
* html .opened .spyHead .spyTitle,
* html .opened .logGroupLabel,
* html .opened .logGroupLabel,
* html .opened .memberLabelCell .memberLabel {
background-image: url(tree_close.gif);
background-repeat: no-repeat;
@@ -1677,7 +1677,7 @@ h1.groupHeader {
/*
.logRow-errorMessage > .hasTwisty > .errorTitle,
.logRow-spy .spyHead .spyTitle,
.logGroup > .logRow
.logGroup > .logRow
*/
.logRow-errorMessage .hasTwisty .errorTitle,
.logRow-spy .spyHead .spyTitle,
@@ -2056,11 +2056,11 @@ h1.groupHeader {
width: 10px;
height: 10px;
margin-top: 6px;
background: url(tabMenuTarget.png);
background: url(tabMenuTarget.png);
}
.fbTabMenuTarget:hover {
background: url(tabMenuTargetHover.png);
background: url(tabMenuTargetHover.png);
}
.fbShadow {
@@ -2098,7 +2098,7 @@ h1.groupHeader {
padding: 1px 18px 0;
text-decoration: none;
color: #000;
cursor: default;
cursor: default;
background: #ACA899;
margin: 4px 0;
}
@@ -2149,7 +2149,7 @@ h1.groupHeader {
}
.fbMenuShortcut {
padding-right: 85px;
padding-right: 85px;
}
.fbMenuShortcutKey {
@@ -2274,7 +2274,7 @@ h1.groupHeader {
margin: 0;
padding: 0;
overflow: hidden;
font-family: Lucida Grande, Tahoma, sans-serif;
font-size: 11px;
background: #fff;
@@ -2311,7 +2311,7 @@ h1.groupHeader {
margin: 0 5px 0 0;
background: #fff url(search.png) no-repeat 4px 2px !important;
background: #fff url(search.gif) no-repeat 4px 2px;
padding-left: 20px;
padding-left: 20px;
font-size: 11px;
}
@@ -2333,7 +2333,7 @@ h1.groupHeader {
background: url(errorIcon.png) no-repeat !important;
background: url(errorIcon.gif) no-repeat;
color: #f00;
font-weight: bold;
font-weight: bold;
}
#fbMiniErrors {
@@ -2348,7 +2348,7 @@ h1.groupHeader {
margin: 3px 4px 0;
height: 20px;
width: 20px;
float: right;
float: right;
background: url(sprite.png) 0 -135px;
cursor: pointer;
}
@@ -2403,10 +2403,10 @@ h1.groupHeader {
}
/************************************************************************************************
Sub-Layout
Sub-Layout
*************************************************************************************************/
/* fbToolbar
/* fbToolbar
*************************************************************************************************/
#fbToolbarIcon {
float: left;
@@ -2472,7 +2472,7 @@ h1.groupHeader {
#fbStatusBarBox {
top: 4px;
cursor: default;
cursor: default;
}
.fbToolbarSeparator {
@@ -2500,7 +2500,7 @@ h1.groupHeader {
.fbStatusBar a:hover {
color: blue;
cursor: pointer;
cursor: pointer;
}
@@ -2545,7 +2545,7 @@ h1.groupHeader {
padding-left: 4px;
}
/* body
/* body
*************************************************************************************************/
.fbPanel {
display: none;
@@ -2609,7 +2609,7 @@ h1.groupHeader {
position: absolute;
right: 2px;
bottom: 3px;
z-index: 99;
}
@@ -2624,7 +2624,7 @@ h1.groupHeader {
visibility: hidden !important;
}
/* fbBottom
/* fbBottom
*************************************************************************************************/
#fbCommand {
@@ -2689,7 +2689,7 @@ div.fbFitHeight {
Layout Controls
*************************************************************************************************/
/* fbToolbar buttons
/* fbToolbar buttons
*************************************************************************************************/
.fbSmallButton {
overflow: hidden;
@@ -2729,7 +2729,7 @@ div.fbFitHeight {
}
/* fbPanelBarBox tabs
/* fbPanelBarBox tabs
*************************************************************************************************/
.fbTab {
text-decoration: none;
@@ -2785,7 +2785,7 @@ a.fbTab:hover .fbTabR {
background: url(sprite.png) -8px -96px !important;
}
/* splitters
/* splitters
*************************************************************************************************/
#fbHSplitter {
position: fixed;
@@ -2888,7 +2888,7 @@ div.objectBox-element {
position: relative;
}
/* Webkit CSS Hack - bug in "highlight" named color */
/* Webkit CSS Hack - bug in "highlight" named color */
@media screen and (-webkit-min-device-pixel-ratio:0) {
.selectedElement{
background: #316AC5;
@@ -2903,7 +2903,7 @@ div.objectBox-element {
}
/* TODO: remove this? */
/* TODO: xxxpedro - IE need this in windowless mode (cnn.com) check if the issue is related to
/* TODO: xxxpedro - IE need this in windowless mode (cnn.com) check if the issue is related to
position. if so, override it at chrome.js initialization when creating the div */
.logRow {
position: relative;
@@ -2939,9 +2939,9 @@ position. if so, override it at chrome.js initialization when creating the div *
.objectBox-string {
color: red;
/* TODO: xxxpedro make long strings break line */
/*white-space: pre; */
/*white-space: pre; */
}
.objectBox-number {

View File

@@ -14,71 +14,71 @@
<tr>
<!-- Interface - Top Area -->
<td id="fbTop" colspan="2">
<!--
<!--
<div>
--><!-- <span id="fbToolbarErrors" class="fbErrors">2 errors</span> --><!--
--><!-- <span id="fbToolbarErrors" class="fbErrors">2 errors</span> --><!--
<input type="text" id="fbToolbarSearch" />
</div>
-->
<!-- Window Buttons -->
<div id="fbWindowButtons">
<a id="fbWindow_btDeactivate" class="fbSmallButton fbHover" title="Deactivate Firebug for this web page">&nbsp;</a>
<a id="fbWindow_btDetach" class="fbSmallButton fbHover" title="Open Firebug in popup window">&nbsp;</a>
<a id="fbWindow_btClose" class="fbSmallButton fbHover" title="Minimize Firebug">&nbsp;</a>
</div>
<!-- Toolbar buttons and Status Bar -->
<div id="fbToolbar">
<div id="fbToolbarContent">
<!-- Firebug Button -->
<span id="fbToolbarIcon">
<a id="fbFirebugButton" class="fbIconButton" class="fbHover" target="_blank">&nbsp;</a>
</span>
<!--
<!--
<span id="fbLeftToolbarErrors" class="fbErrors">2 errors</span>
-->
<!-- Toolbar Buttons -->
<span id="fbToolbarButtons">
<!-- Fixed Toolbar Buttons -->
<span id="fbFixedButtons">
<a id="fbChrome_btInspect" class="fbButton fbHover" title="Click an element in the page to inspect">Inspect</a>
</span>
<!-- Console Panel Toolbar Buttons -->
<span id="fbConsoleButtons" class="fbToolbarButtons">
<a id="fbConsole_btClear" class="fbButton fbHover" title="Clear the console">Clear</a>
</span>
<!-- HTML Panel Toolbar Buttons -->
<!--
<!--
<span id="fbHTMLButtons" class="fbToolbarButtons">
<a id="fbHTML_btEdit" class="fbHover" title="Edit this HTML">Edit</a>
</span>
-->
</span>
<!-- Status Bar -->
<span id="fbStatusBarBox">
<span class="fbToolbarSeparator"></span>
<!-- HTML Panel Status Bar -->
<!--
<!--
<span id="fbHTMLStatusBar" class="fbStatusBar fbToolbarButtons">
</span>
-->
</span>
</div>
</div>
<!-- PanelBars -->
<div id="fbPanelBarBox">
<!-- Main PanelBar -->
<div id="fbPanelBar1" class="fbPanelBar">
<a id="fbConsoleTab" class="fbTab fbHover">
@@ -112,7 +112,7 @@
<!-- Side PanelBars -->
<div id="fbPanelBar2Box" class="hide">
<div id="fbPanelBar2" class="fbPanelBar">
<!--
<!--
<a class="fbTab fbHover">
<span class="fbTabL"></span>
<span class="fbTabText">Style</span>
@@ -131,18 +131,18 @@
-->
</div>
</div>
</div>
<!-- Horizontal Splitter -->
<div id="fbHSplitter">&nbsp;</div>
</td>
</tr>
<!-- Interface - Main Area -->
<tr id="fbContent">
<!-- Panels -->
<td id="fbPanelBox1">
<div id="fbPanel1" class="fbFitHeight">
@@ -150,41 +150,41 @@
<div id="fbHTML" class="fbPanel"></div>
</div>
</td>
<!-- Side Panel Box -->
<td id="fbPanelBox2" class="hide">
<!-- VerticalSplitter -->
<div id="fbVSplitter" class="fbVSplitter">&nbsp;</div>
<!-- Side Panels -->
<div id="fbPanel2" class="fbFitHeight">
<!-- HTML Side Panels -->
<div id="fbHTML_Style" class="fbPanel"></div>
<div id="fbHTML_Layout" class="fbPanel"></div>
<div id="fbHTML_DOM" class="fbPanel"></div>
</div>
<!-- Large Command Line -->
<textarea id="fbLargeCommandLine" class="fbFitHeight"></textarea>
<!-- Large Command Line Buttons -->
<div id="fbLargeCommandButtons">
<a id="fbCommand_btRun" class="fbButton fbHover">Run</a>
<a id="fbCommand_btClear" class="fbButton fbHover">Clear</a>
<a id="fbSmallCommandLineIcon" class="fbSmallButton fbHover"></a>
</div>
</td>
</tr>
<!-- Interface - Bottom Area -->
<tr id="fbBottom" class="hide">
<!-- Command Line -->
<td id="fbCommand" colspan="2">
<div id="fbCommandBox">
@@ -193,18 +193,18 @@
<a id="fbLargeCommandLineIcon" class="fbSmallButton fbHover"></a>
</div>
</td>
</tr>
</tbody>
</table>
</table>
<span id="fbMiniChrome">
<span id="fbMiniContent">
<span id="fbMiniIcon" title="Open Firebug Lite"></span>
<span id="fbMiniErrors" class="fbErrors"><!-- 2 errors --></span>
</span>
</span>
<!--
<!--
<div id="fbErrorPopup">
<div id="fbErrorPopupContent">
<div id="fbErrorIndicator" class="fbErrors">2 errors</div>

View File

@@ -6258,7 +6258,7 @@ FBL.Firebug =
{
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
version: "Firebug Lite 1.4.0",
revision: "$Revision$",
revision: "$Revision: 11967 $",
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
modules: modules,

21
vendor/jquery/MIT-LICENSE.txt vendored Normal file
View File

@@ -0,0 +1,21 @@
Copyright 2012 jQuery Foundation and other contributors
http://jquery.com/
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.

417
vendor/jquery/README.md vendored Normal file
View File

@@ -0,0 +1,417 @@
[jQuery](http://jquery.com/) - New Wave JavaScript
==================================================
Contribution Guides
--------------------------------------
In the spirit of open source software development, jQuery always encourages community code contribution. To help you get started and before you jump into writing code, be sure to read these important contribution guidelines thoroughly:
1. [Getting Involved](http://docs.jquery.com/Getting_Involved)
2. [Core Style Guide](http://docs.jquery.com/JQuery_Core_Style_Guidelines)
3. [Tips For Bug Patching](http://docs.jquery.com/Tips_for_jQuery_Bug_Patching)
What you need to build your own jQuery
--------------------------------------
In order to build jQuery, you need to have GNU make 3.8 or later, Node.js/npm latest, and git 1.7 or later.
(Earlier versions might work OK, but are not tested.)
Windows users have two options:
1. Install [msysgit](https://code.google.com/p/msysgit/) (Full installer for official Git),
[GNU make for Windows](http://gnuwin32.sourceforge.net/packages/make.htm), and a
[binary version of Node.js](http://node-js.prcn.co.cc/). Make sure all three packages are installed to the same
location (by default, this is C:\Program Files\Git).
2. Install [Cygwin](http://cygwin.com/) (make sure you install the git, make, and which packages), then either follow
the [Node.js build instructions](https://github.com/ry/node/wiki/Building-node.js-on-Cygwin-%28Windows%29) or install
the [binary version of Node.js](http://node-js.prcn.co.cc/).
Mac OS users should install Xcode (comes on your Mac OS install DVD, or downloadable from
[Apple's Xcode site](http://developer.apple.com/technologies/xcode.html)) and
[Homebrew](http://mxcl.github.com/homebrew/). Once Homebrew is installed, run `brew install git` to install git,
and `brew install node` to install Node.js.
Linux/BSD users should use their appropriate package managers to install make, git, and node, or build from source
if you swing that way. Easy-peasy.
How to build your own jQuery
----------------------------
First, clone a copy of the main jQuery git repo by running:
```bash
git clone git://github.com/jquery/jquery.git
```
Enter the directory and install the Node dependencies:
```bash
cd jquery && npm install
```
Make sure you have `grunt` installed by testing:
```bash
grunt -version
```
Then, to get a complete, minified (w/ Uglify.js), linted (w/ JSHint) version of jQuery, type the following:
```bash
grunt
```
The built version of jQuery will be put in the `dist/` subdirectory.
### Modules (new in 1.8)
Starting in jQuery 1.8, special builds can now be created that optionally exclude or include any of the following modules:
- ajax
- css
- dimensions
- effects
- offset
Before creating a custom build for use in production, be sure to check out the latest stable version:
```bash
git pull; git checkout $(git describe --abbrev=0 --tags)
```
Then, make sure all Node dependencies are installed and all Git submodules are checked out:
```bash
npm install && grunt
```
To create a custom build, use the following special `grunt` commands:
Exclude **ajax**:
```bash
grunt custom:-ajax
```
Exclude **css**:
```bash
grunt custom:-css
```
Exclude **deprecated**:
```bash
grunt custom:-deprecated
```
Exclude **dimensions**:
```bash
grunt custom:-dimensions
```
Exclude **effects**:
```bash
grunt custom:-effects
```
Exclude **offset**:
```bash
grunt custom:-offset
```
Exclude **all** optional modules:
```bash
grunt custom:-ajax,-css,-deprecated,-dimensions,-effects,-offset
```
Note: dependencies will be handled internally, by the build process.
Running the Unit Tests
--------------------------------------
Start grunt to auto-build jQuery as you work:
```bash
cd jquery && grunt watch
```
Run the unit tests with a local server that supports PHP. No database is required. Pre-configured php local servers are available for Windows and Mac. Here are some options:
- Windows: [WAMP download](http://www.wampserver.com/en/)
- Mac: [MAMP download](http://www.mamp.info/en/index.html)
- Linux: [Setting up LAMP](https://www.linux.com/learn/tutorials/288158-easy-lamp-server-installation)
- [Mongoose (most platforms)](http://code.google.com/p/mongoose/)
Building to a different directory
---------------------------------
If you want to build jQuery to a directory that is different from the default location:
```bash
grunt && grunt dist:/path/to/special/location/
```
With this example, the output files would be:
```bash
/path/to/special/location/jquery.js
/path/to/special/location/jquery.min.js
```
If you want to add a permanent copy destination, create a file in `dist/` called ".destination.json". Inside the file, paste and customize the following:
```json
{
"/Absolute/path/to/other/destination": true
}
```
Additionally, both methods can be combined.
Updating Submodules
-------------------
Update the submodules to what is probably the latest upstream code.
```bash
grunt update_submodules
```
Note: This task will also be run any time the default `grunt` command is used.
Git for dummies
---------------
As the source code is handled by the version control system Git, it's useful to know some features used.
### Submodules ###
The repository uses submodules, which normally are handled directly by the Makefile, but sometimes you want to
be able to work with them manually.
Following are the steps to manually get the submodules:
```bash
git clone https://github.com/jquery/jquery.git
cd jquery
git submodule init
git submodule update
```
Or:
```bash
git clone https://github.com/jquery/jquery.git
cd jquery
git submodule update --init
```
Or:
```bash
git clone --recursive https://github.com/jquery/jquery.git
cd jquery
```
If you want to work inside a submodule, it is possible, but first you need to checkout a branch:
```bash
cd src/sizzle
git checkout master
```
After you've committed your changes to the submodule, you'll update the jquery project to point to the new commit,
but remember to push the submodule changes before pushing the new jquery commit:
```bash
cd src/sizzle
git push origin master
cd ..
git add src/sizzle
git commit
```
### cleaning ###
If you want to purge your working directory back to the status of upstream, following commands can be used (remember everything you've worked on is gone after these):
```bash
git reset --hard upstream/master
git clean -fdx
```
### rebasing ###
For feature/topic branches, you should always used the `--rebase` flag to `git pull`, or if you are usually handling many temporary "to be in a github pull request" branches, run following to automate this:
```bash
git config branch.autosetuprebase local
```
(see `man git-config` for more information)
### handling merge conflicts ###
If you're getting merge conflicts when merging, instead of editing the conflicted files manually, you can use the feature
`git mergetool`. Even though the default tool `xxdiff` looks awful/old, it's rather useful.
Following are some commands that can be used there:
* `Ctrl + Alt + M` - automerge as much as possible
* `b` - jump to next merge conflict
* `s` - change the order of the conflicted lines
* `u` - undo an merge
* `left mouse button` - mark a block to be the winner
* `middle mouse button` - mark a line to be the winner
* `Ctrl + S` - save
* `Ctrl + Q` - quit
[QUnit](http://docs.jquery.com/QUnit) Reference
-----------------
### Test methods ###
```js
expect( numAssertions );
stop();
start();
```
note: QUnit's eventual addition of an argument to stop/start is ignored in this test suite so that start and stop can be passed as callbacks without worrying about their parameters
### Test assertions ###
```js
ok( value, [message] );
equal( actual, expected, [message] );
notEqual( actual, expected, [message] );
deepEqual( actual, expected, [message] );
notDeepEqual( actual, expected, [message] );
strictEqual( actual, expected, [message] );
notStrictEqual( actual, expected, [message] );
raises( block, [expected], [message] );
```
Test Suite Convenience Methods Reference (See [test/data/testinit.js](https://github.com/jquery/jquery/blob/master/test/data/testinit.js))
------------------------------
### Returns an array of elements with the given IDs ###
```js
q( ... );
```
Example:
```js
q("main", "foo", "bar");
=> [ div#main, span#foo, input#bar ]
```
### Asserts that a selection matches the given IDs ###
```js
t( testName, selector, [ "array", "of", "ids" ] );
```
Example:
```js
t("Check for something", "//[a]", ["foo", "baar"]);
```
### Fires a native DOM event without going through jQuery ###
```js
fireNative( node, eventType )
```
Example:
```js
fireNative( jQuery("#elem")[0], "click" );
```
### Add random number to url to stop caching ###
```js
url( "some/url.php" );
```
Example:
```js
url("data/test.html");
=> "data/test.html?10538358428943"
url("data/test.php?foo=bar");
=> "data/test.php?foo=bar&10538358345554"
```
### Load tests in an iframe ###
Loads a given page constructing a url with fileName: `"./data/" + fileName + ".html"`
and fires the given callback on jQuery ready (using the jQuery loading from that page)
and passes the iFrame's jQuery to the callback.
```js
testIframe( fileName, testName, callback );
```
Callback arguments:
```js
callback( jQueryFromIFrame, iFrameWindow, iFrameDocument );
```
### Load tests in an iframe (window.iframeCallback) ###
Loads a given page constructing a url with fileName: `"./data/" + fileName + ".html"`
The given callback is fired when window.iframeCallback is called by the page
The arguments passed to the callback are the same as the
arguments passed to window.iframeCallback, whatever that may be
```js
testIframeWithCallback( testName, fileName, callback );
```
Questions?
----------
If you have any questions, please feel free to ask on the
[Developing jQuery Core forum](http://forum.jquery.com/developing-jquery-core) or in #jquery on irc.freenode.net.

9440
vendor/jquery/jquery.js vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,512 +0,0 @@
/*
json2.js
2015-02-25
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or '&nbsp;'),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10
? '0' + n
: n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint
eval, for, this
*/
/*property
JSON, apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
if (typeof JSON !== 'object') {
JSON = {};
}
(function () {
'use strict';
function f(n) {
// Format integers to have at least two digits.
return n < 10
? '0' + n
: n;
}
function this_value() {
return this.valueOf();
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function () {
return isFinite(this.valueOf())
? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z'
: null;
};
Boolean.prototype.toJSON = this_value;
Number.prototype.toJSON = this_value;
String.prototype.toJSON = this_value;
}
var cx,
escapable,
gap,
indent,
meta,
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string)
? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string'
? c
: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"'
: '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value)
? String(value)
: 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0
? '[]'
: gap
? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
: '[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (
gap
? ': '
: ':'
) + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (
gap
? ': '
: ':'
) + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0
? '{}'
: gap
? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
: '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
escapable = /[\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"': '\\"',
'\\': '\\\\'
};
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (
/^[\],:{}\s]*$/.test(
text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, '')
)
) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function'
? walk({'': j}, '')
: j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
}());

20
vendor/json3/LICENSE vendored Normal file
View File

@@ -0,0 +1,20 @@
Copyright (c) 2012 Kit Cambridge.
http://kitcambridge.github.com
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.

124
vendor/json3/README.md vendored Normal file
View File

@@ -0,0 +1,124 @@
# JSON 3 #
![JSON 3 Logo](http://bestiejs.github.com/json3/page/logo.png)
**JSON 3** is a modern JSON implementation compatible with a variety of JavaScript platforms, including Internet Explorer 6, Opera 7, Safari 2, and Netscape 6. The current version is **3.2.4**.
- [Development Version](http://cdnjs.cloudflare.com/ajax/libs/json3/3.2.4/json3.js) *(36.5 KB; uncompressed with comments)*
- [Production Version](http://cdnjs.cloudflare.com/ajax/libs/json3/3.2.4/json3.min.js) *(3.0 KB; compressed and `gzip`-ped)*
[JSON](http://json.org/) is a language-independent data interchange format based on a loose subset of the JavaScript grammar. Originally popularized by [Douglas Crockford](http://www.crockford.com/), the format was standardized in the [fifth edition](http://es5.github.com/) of the ECMAScript specification. The 5.1 edition, ratified in June 2011, incorporates several modifications to the grammar pertaining to the serialization of dates.
JSON 3 exposes two functions: `stringify()` for [serializing](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/stringify) a JavaScript value to JSON, and `parse()` for [producing](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/parse) a JavaScript value from a JSON source string. It is a **drop-in replacement** for [JSON 2](http://json.org/js). The functions behave exactly as described in the ECMAScript spec, **except** for the date serialization discrepancy noted below.
The JSON 3 parser does **not** use `eval` or regular expressions. This provides security and performance benefits in obsolete and mobile environments, where the margin is particularly significant. The complete [benchmark suite](http://jsperf.com/json3) is available on [jsPerf](http://jsperf.com/).
The project is [hosted on GitHub](http://git.io/json3), along with the [unit tests](http://bestiejs.github.com/json3/test/test_browser.html). It is part of the [BestieJS](https://github.com/bestiejs) family, a collection of best-in-class JavaScript libraries that promote cross-platform support, specification precedents, unit testing, and plenty of documentation.
# Changes from JSON 2 #
JSON 3...
* Correctly serializes primitive wrapper objects.
* Throws a `TypeError` when serializing cyclic structures (JSON 2 recurses until the call stack overflows).
* Utilizes **feature tests** to detect broken or incomplete *native* JSON implementations (JSON 2 only checks for the presence of the native functions). The tests are only executed once at runtime, so there is no additional performance cost when parsing or serializing values.
**As of v3.2.3**, JSON 3 is compatible with [Prototype](http://prototypejs.org) 1.6.1 and older.
In contrast to JSON 2, JSON 3 **does not**...
* Add `toJSON()` methods to the `Boolean`, `Number`, and `String` prototypes. These are not part of any standard, and are made redundant by the design of the `stringify()` implementation.
* Add `toJSON()` or `toISOString()` methods to `Date.prototype`. See the note about date serialization below.
## Date Serialization
**JSON 3 deviates from the specification in one important way**: it does not define `Date#toISOString()` or `Date#toJSON()`. This preserves CommonJS compatibility and avoids polluting native prototypes. Instead, date serialization is performed internally by the `stringify()` implementation: if a date object does not define a custom `toJSON()` method, it is serialized as a [simplified ISO 8601 date-time string](http://es5.github.com/#x15.9.1.15).
**Several native `Date#toJSON()` implementations produce date time strings that do *not* conform to the grammar outlined in the spec**. For instance, all versions of Safari 4, as well as JSON 2, fail to serialize extended years correctly. Furthermore, JSON 2 and older implementations omit the milliseconds from the date-time string (optional in ES 5, but required in 5.1). Finally, in all versions of Safari 4 and 5, serializing an invalid date will produce the string `"Invalid Date"`, rather than `null`. Because these environments exhibit other serialization bugs, however, JSON 3 will override the native `stringify()` implementation.
Portions of the date serialization code are adapted from the [`date-shim`](https://github.com/Yaffle/date-shim) project.
# Usage #
## Web Browsers
<script src="//cdnjs.cloudflare.com/ajax/libs/json3/3.2.4/json3.min.js"></script>
<script>
JSON.stringify({"Hello": 123});
// => '{"Hello":123}'
JSON.parse("[[1, 2, 3], 1, 2, 3, 4]", function (key, value) {
if (typeof value == "number") {
value = value % 2 ? "Odd" : "Even";
}
return value;
});
// => [["Odd", "Even", "Odd"], "Odd", "Even", "Odd", "Even"]
</script>
## CommonJS Environments
var JSON3 = require("./path/to/json3");
JSON3.parse("[1, 2, 3]");
// => [1, 2, 3]
## JavaScript Engines
load("path/to/json3.js");
JSON.stringify({"Hello": 123, "Good-bye": 456}, ["Hello"], "\t");
// => '{\n\t"Hello": 123\n}'
# Compatibility #
JSON 3 has been **tested** with the following web browsers, CommonJS environments, and JavaScript engines.
## Web Browsers
- Windows [Internet Explorer](http://www.microsoft.com/windows/internet-explorer), version 6.0 and higher
- Mozilla [Firefox](http://www.mozilla.com/firefox), version 1.0 and higher
- Apple [Safari](http://www.apple.com/safari), version 2.0 and higher
- [Opera](http://www.opera.com) 7.02 and higher
- [Mozilla](http://sillydog.org/narchive/gecko.php) 1.0, [Netscape](http://sillydog.org/narchive/) 6.2.3, and [SeaMonkey](http://www.seamonkey-project.org/) 1.0 and higher
## CommonJS Environments
- [Node](http://nodejs.org/) 0.2.6 and higher
- [RingoJS](http://ringojs.org/) 0.4 and higher
- [Narwhal](http://narwhaljs.org/) 0.3.2 and higher
## JavaScript Engines
- Mozilla [Rhino](http://www.mozilla.org/rhino) 1.5R5 and higher
- WebKit [JSC](https://trac.webkit.org/wiki/JSC)
- Google [V8](http://code.google.com/p/v8)
## Known Incompatibilities
* Attempting to serialize the `arguments` object may produce inconsistent results across environments due to specification version differences. As a workaround, please convert the `arguments` object to an array first: `JSON.stringify([].slice.call(arguments, 0))`.
## Required Native Methods
JSON 3 assumes that the following methods exist and function as described in the ECMAScript specification:
- The `Number`, `String`, `Array`, `Object`, `Date`, `SyntaxError`, and `TypeError` constructors.
- `String.fromCharCode`
- `Object#toString`
- `Function#call`
- `Math.floor`
- `Number#toString`
- `Date#valueOf`
- `String.prototype`: `indexOf`, `charCodeAt`, `charAt`, `slice`.
- `Array.prototype`: `push`, `pop`, `join`.
# Contribute #
Check out a working copy of the JSON 3 source code with [Git](http://git-scm.com/):
$ git clone git://github.com/bestiejs/json3.git
$ cd json3
$ git submodule update --init
If you'd like to contribute a feature or bug fix, you can [fork](http://help.github.com/fork-a-repo/) JSON 3, commit your changes, and [send a pull request](http://help.github.com/send-pull-requests/). Please make sure to update the unit tests in the `test` directory as well.
Alternatively, you can use the [GitHub issue tracker](https://github.com/bestiejs/json3/issues) to submit bug reports, feature requests, and questions, or send tweets to [@kitcambridge](http://twitter.com/kitcambridge).
JSON 3 is released under the [MIT License](http://kit.mit-license.org/).

783
vendor/json3/lib/json3.js vendored Normal file
View File

@@ -0,0 +1,783 @@
/*! JSON v3.2.4 | http://bestiejs.github.com/json3 | Copyright 2012, Kit Cambridge | http://kit.mit-license.org */
;(function () {
// Convenience aliases.
var getClass = {}.toString, isProperty, forEach, undef;
// Detect the `define` function exposed by asynchronous module loaders. The
// strict `define` check is necessary for compatibility with `r.js`.
var isLoader = typeof define === "function" && define.amd, JSON3 = !isLoader && typeof exports == "object" && exports;
if (JSON3 || isLoader) {
if (typeof JSON == "object" && JSON) {
// Delegate to the native `stringify` and `parse` implementations in
// asynchronous module loaders and CommonJS environments.
if (isLoader) {
JSON3 = JSON;
} else {
JSON3.stringify = JSON.stringify;
JSON3.parse = JSON.parse;
}
} else if (isLoader) {
JSON3 = this.JSON = {};
}
} else {
// Export for web browsers and JavaScript engines.
JSON3 = this.JSON || (this.JSON = {});
}
// Local variables.
var Escapes, toPaddedString, quote, serialize;
var fromCharCode, Unescapes, abort, lex, get, walk, update, Index, Source;
// Test the `Date#getUTC*` methods. Based on work by @Yaffle.
var isExtended = new Date(-3509827334573292), floor, Months, getDay;
try {
// The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
// results for certain dates in Opera >= 10.53.
isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() == 1 &&
// Safari < 2.0.2 stores the internal millisecond time value correctly,
// but clips the values returned by the date methods to the range of
// signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
} catch (exception) {}
// Internal: Determines whether the native `JSON.stringify` and `parse`
// implementations are spec-compliant. Based on work by Ken Snyder.
function has(name) {
var stringifySupported, parseSupported, value, serialized = '{"A":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}', all = name == "json";
if (all || name == "json-stringify" || name == "json-parse") {
// Test `JSON.stringify`.
if (name == "json-stringify" || all) {
if ((stringifySupported = typeof JSON3.stringify == "function" && isExtended)) {
// A test function object with a custom `toJSON` method.
(value = function () {
return 1;
}).toJSON = value;
try {
stringifySupported =
// Firefox 3.1b1 and b2 serialize string, number, and boolean
// primitives as object literals.
JSON3.stringify(0) === "0" &&
// FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
// literals.
JSON3.stringify(new Number()) === "0" &&
JSON3.stringify(new String()) == '""' &&
// FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
// does not define a canonical JSON representation (this applies to
// objects with `toJSON` properties as well, *unless* they are nested
// within an object or array).
JSON3.stringify(getClass) === undef &&
// IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
// FF 3.1b3 pass this test.
JSON3.stringify(undef) === undef &&
// Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
// respectively, if the value is omitted entirely.
JSON3.stringify() === undef &&
// FF 3.1b1, 2 throw an error if the given value is not a number,
// string, array, object, Boolean, or `null` literal. This applies to
// objects with custom `toJSON` methods as well, unless they are nested
// inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
// methods entirely.
JSON3.stringify(value) === "1" &&
JSON3.stringify([value]) == "[1]" &&
// Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
// `"[null]"`.
JSON3.stringify([undef]) == "[null]" &&
// YUI 3.0.0b1 fails to serialize `null` literals.
JSON3.stringify(null) == "null" &&
// FF 3.1b1, 2 halts serialization if an array contains a function:
// `[1, true, getClass, 1]` serializes as "[1,true,],". These versions
// of Firefox also allow trailing commas in JSON objects and arrays.
// FF 3.1b3 elides non-JSON values from objects and arrays, unless they
// define custom `toJSON` methods.
JSON3.stringify([undef, getClass, null]) == "[null,null,null]" &&
// Simple serialization test. FF 3.1b1 uses Unicode escape sequences
// where character escape codes are expected (e.g., `\b` => `\u0008`).
JSON3.stringify({ "A": [value, true, false, null, "\0\b\n\f\r\t"] }) == serialized &&
// FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
JSON3.stringify(null, value) === "1" &&
JSON3.stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
// JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
// serialize extended years.
JSON3.stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
// The milliseconds are optional in ES 5, but required in 5.1.
JSON3.stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
// Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
// four-digit years instead of six-digit years. Credits: @Yaffle.
JSON3.stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
// Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
// values less than 1000. Credits: @Yaffle.
JSON3.stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
} catch (exception) {
stringifySupported = false;
}
}
if (!all) {
return stringifySupported;
}
}
// Test `JSON.parse`.
if (name == "json-parse" || all) {
if (typeof JSON3.parse == "function") {
try {
// FF 3.1b1, b2 will throw an exception if a bare literal is provided.
// Conforming implementations should also coerce the initial argument to
// a string prior to parsing.
if (JSON3.parse("0") === 0 && !JSON3.parse(false)) {
// Simple parsing test.
value = JSON3.parse(serialized);
if ((parseSupported = value.A.length == 5 && value.A[0] == 1)) {
try {
// Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
parseSupported = !JSON3.parse('"\t"');
} catch (exception) {}
if (parseSupported) {
try {
// FF 4.0 and 4.0.1 allow leading `+` signs, and leading and
// trailing decimal points. FF 4.0, 4.0.1, and IE 9-10 also
// allow certain octal literals.
parseSupported = JSON3.parse("01") != 1;
} catch (exception) {}
}
}
}
} catch (exception) {
parseSupported = false;
}
}
if (!all) {
return parseSupported;
}
}
return stringifySupported && parseSupported;
}
}
if (!has("json")) {
// Define additional utility methods if the `Date` methods are buggy.
if (!isExtended) {
floor = Math.floor;
// A mapping between the months of the year and the number of days between
// January 1st and the first of the respective month.
Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
// Internal: Calculates the number of days between the Unix epoch and the
// first day of the given month.
getDay = function (year, month) {
return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
};
}
// Internal: Determines if a property is a direct property of the given
// object. Delegates to the native `Object#hasOwnProperty` method.
if (!(isProperty = {}.hasOwnProperty)) {
isProperty = function (property) {
var members = {}, constructor;
if ((members.__proto__ = null, members.__proto__ = {
// The *proto* property cannot be set multiple times in recent
// versions of Firefox and SeaMonkey.
"toString": 1
}, members).toString != getClass) {
// Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
// supports the mutable *proto* property.
isProperty = function (property) {
// Capture and break the object's prototype chain (see section 8.6.2
// of the ES 5.1 spec). The parenthesized expression prevents an
// unsafe transformation by the Closure Compiler.
var original = this.__proto__, result = property in (this.__proto__ = null, this);
// Restore the original prototype chain.
this.__proto__ = original;
return result;
};
} else {
// Capture a reference to the top-level `Object` constructor.
constructor = members.constructor;
// Use the `constructor` property to simulate `Object#hasOwnProperty` in
// other environments.
isProperty = function (property) {
var parent = (this.constructor || constructor).prototype;
return property in this && !(property in parent && this[property] === parent[property]);
};
}
members = null;
return isProperty.call(this, property);
};
}
// Internal: Normalizes the `for...in` iteration algorithm across
// environments. Each enumerated key is yielded to a `callback` function.
forEach = function (object, callback) {
var size = 0, Properties, members, property, forEach;
// Tests for bugs in the current environment's `for...in` algorithm. The
// `valueOf` property inherits the non-enumerable flag from
// `Object.prototype` in older versions of IE, Netscape, and Mozilla.
(Properties = function () {
this.valueOf = 0;
}).prototype.valueOf = 0;
// Iterate over a new instance of the `Properties` class.
members = new Properties();
for (property in members) {
// Ignore all properties inherited from `Object.prototype`.
if (isProperty.call(members, property)) {
size++;
}
}
Properties = members = null;
// Normalize the iteration algorithm.
if (!size) {
// A list of non-enumerable properties inherited from `Object.prototype`.
members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
// IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
// properties.
forEach = function (object, callback) {
var isFunction = getClass.call(object) == "[object Function]", property, length;
for (property in object) {
// Gecko <= 1.0 enumerates the `prototype` property of functions under
// certain conditions; IE does not.
if (!(isFunction && property == "prototype") && isProperty.call(object, property)) {
callback(property);
}
}
// Manually invoke the callback for each non-enumerable property.
for (length = members.length; property = members[--length]; isProperty.call(object, property) && callback(property));
};
} else if (size == 2) {
// Safari <= 2.0.4 enumerates shadowed properties twice.
forEach = function (object, callback) {
// Create a set of iterated properties.
var members = {}, isFunction = getClass.call(object) == "[object Function]", property;
for (property in object) {
// Store each property name to prevent double enumeration. The
// `prototype` property of functions is not enumerated due to cross-
// environment inconsistencies.
if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {
callback(property);
}
}
};
} else {
// No bugs detected; use the standard `for...in` algorithm.
forEach = function (object, callback) {
var isFunction = getClass.call(object) == "[object Function]", property, isConstructor;
for (property in object) {
if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
callback(property);
}
}
// Manually invoke the callback for the `constructor` property due to
// cross-environment inconsistencies.
if (isConstructor || isProperty.call(object, (property = "constructor"))) {
callback(property);
}
};
}
return forEach(object, callback);
};
// Public: Serializes a JavaScript `value` as a JSON string. The optional
// `filter` argument may specify either a function that alters how object and
// array members are serialized, or an array of strings and numbers that
// indicates which properties should be serialized. The optional `width`
// argument may be either a string or number that specifies the indentation
// level of the output.
if (!has("json-stringify")) {
// Internal: A map of control characters and their escaped equivalents.
Escapes = {
"\\": "\\\\",
'"': '\\"',
"\b": "\\b",
"\f": "\\f",
"\n": "\\n",
"\r": "\\r",
"\t": "\\t"
};
// Internal: Converts `value` into a zero-padded string such that its
// length is at least equal to `width`. The `width` must be <= 6.
toPaddedString = function (width, value) {
// The `|| 0` expression is necessary to work around a bug in
// Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
return ("000000" + (value || 0)).slice(-width);
};
// Internal: Double-quotes a string `value`, replacing all ASCII control
// characters (characters with code unit values between 0 and 31) with
// their escaped equivalents. This is an implementation of the
// `Quote(value)` operation defined in ES 5.1 section 15.12.3.
quote = function (value) {
var result = '"', index = 0, symbol;
for (; symbol = value.charAt(index); index++) {
// Escape the reverse solidus, double quote, backspace, form feed, line
// feed, carriage return, and tab characters.
result += '\\"\b\f\n\r\t'.indexOf(symbol) > -1 ? Escapes[symbol] :
// If the character is a control character, append its Unicode escape
// sequence; otherwise, append the character as-is.
(Escapes[symbol] = symbol < " " ? "\\u00" + toPaddedString(2, symbol.charCodeAt(0).toString(16)) : symbol);
}
return result + '"';
};
// Internal: Recursively serializes an object. Implements the
// `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
var value = object[property], className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, any, result;
if (typeof value == "object" && value) {
className = getClass.call(value);
if (className == "[object Date]" && !isProperty.call(value, "toJSON")) {
if (value > -1 / 0 && value < 1 / 0) {
// Dates are serialized according to the `Date#toJSON` method
// specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
// for the ISO 8601 date time string format.
if (getDay) {
// Manually compute the year, month, date, hours, minutes,
// seconds, and milliseconds if the `getUTC*` methods are
// buggy. Adapted from @Yaffle's `date-shim` project.
date = floor(value / 864e5);
for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
date = 1 + date - getDay(year, month);
// The `time` value specifies the time within the day (see ES
// 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
// to compute `A modulo B`, as the `%` operator does not
// correspond to the `modulo` operation for negative numbers.
time = (value % 864e5 + 864e5) % 864e5;
// The hours, minutes, seconds, and milliseconds are obtained by
// decomposing the time within the day. See section 15.9.1.10.
hours = floor(time / 36e5) % 24;
minutes = floor(time / 6e4) % 60;
seconds = floor(time / 1e3) % 60;
milliseconds = time % 1e3;
} else {
year = value.getUTCFullYear();
month = value.getUTCMonth();
date = value.getUTCDate();
hours = value.getUTCHours();
minutes = value.getUTCMinutes();
seconds = value.getUTCSeconds();
milliseconds = value.getUTCMilliseconds();
}
// Serialize extended years correctly.
value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
"-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
// Months, dates, hours, minutes, and seconds should have two
// digits; milliseconds should have three.
"T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
// Milliseconds are optional in ES 5.0, but required in 5.1.
"." + toPaddedString(3, milliseconds) + "Z";
} else {
value = null;
}
} else if (typeof value.toJSON == "function" && ((className != "[object Number]" && className != "[object String]" && className != "[object Array]") || isProperty.call(value, "toJSON"))) {
// Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
// `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
// ignores all `toJSON` methods on these objects unless they are
// defined directly on an instance.
value = value.toJSON(property);
}
}
if (callback) {
// If a replacement function was provided, call it to obtain the value
// for serialization.
value = callback.call(object, property, value);
}
if (value === null) {
return "null";
}
className = getClass.call(value);
if (className == "[object Boolean]") {
// Booleans are represented literally.
return "" + value;
} else if (className == "[object Number]") {
// JSON numbers must be finite. `Infinity` and `NaN` are serialized as
// `"null"`.
return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
} else if (className == "[object String]") {
// Strings are double-quoted and escaped.
return quote(value);
}
// Recursively serialize objects and arrays.
if (typeof value == "object") {
// Check for cyclic structures. This is a linear search; performance
// is inversely proportional to the number of unique nested objects.
for (length = stack.length; length--;) {
if (stack[length] === value) {
// Cyclic structures cannot be serialized by `JSON.stringify`.
throw TypeError();
}
}
// Add the object to the stack of traversed objects.
stack.push(value);
results = [];
// Save the current indentation level and indent one additional level.
prefix = indentation;
indentation += whitespace;
if (className == "[object Array]") {
// Recursively serialize array elements.
for (index = 0, length = value.length; index < length; any || (any = true), index++) {
element = serialize(index, value, callback, properties, whitespace, indentation, stack);
results.push(element === undef ? "null" : element);
}
result = any ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
} else {
// Recursively serialize object members. Members are selected from
// either a user-specified list of property names, or the object
// itself.
forEach(properties || value, function (property) {
var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
if (element !== undef) {
// According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
// is not the empty string, let `member` {quote(property) + ":"}
// be the concatenation of `member` and the `space` character."
// The "`space` character" refers to the literal space
// character, not the `space` {width} argument provided to
// `JSON.stringify`.
results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
}
any || (any = true);
});
result = any ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
}
// Remove the object from the traversed object stack.
stack.pop();
return result;
}
};
// Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
JSON3.stringify = function (source, filter, width) {
var whitespace, callback, properties, index, length, value;
if (typeof filter == "function" || typeof filter == "object" && filter) {
if (getClass.call(filter) == "[object Function]") {
callback = filter;
} else if (getClass.call(filter) == "[object Array]") {
// Convert the property names array into a makeshift set.
properties = {};
for (index = 0, length = filter.length; index < length; value = filter[index++], ((getClass.call(value) == "[object String]" || getClass.call(value) == "[object Number]") && (properties[value] = 1)));
}
}
if (width) {
if (getClass.call(width) == "[object Number]") {
// Convert the `width` to an integer and create a string containing
// `width` number of space characters.
if ((width -= width % 1) > 0) {
for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");
}
} else if (getClass.call(width) == "[object String]") {
whitespace = width.length <= 10 ? width : width.slice(0, 10);
}
}
// Opera <= 7.54u2 discards the values associated with empty string keys
// (`""`) only if they are used directly within an object member list
// (e.g., `!("" in { "": 1})`).
return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
};
}
// Public: Parses a JSON source string.
if (!has("json-parse")) {
fromCharCode = String.fromCharCode;
// Internal: A map of escaped control characters and their unescaped
// equivalents.
Unescapes = {
"\\": "\\",
'"': '"',
"/": "/",
"b": "\b",
"t": "\t",
"n": "\n",
"f": "\f",
"r": "\r"
};
// Internal: Resets the parser state and throws a `SyntaxError`.
abort = function() {
Index = Source = null;
throw SyntaxError();
};
// Internal: Returns the next token, or `"$"` if the parser has reached
// the end of the source string. A token may be a string, number, `null`
// literal, or Boolean literal.
lex = function () {
var source = Source, length = source.length, symbol, value, begin, position, sign;
while (Index < length) {
symbol = source.charAt(Index);
if ("\t\r\n ".indexOf(symbol) > -1) {
// Skip whitespace tokens, including tabs, carriage returns, line
// feeds, and space characters.
Index++;
} else if ("{}[]:,".indexOf(symbol) > -1) {
// Parse a punctuator token at the current position.
Index++;
return symbol;
} else if (symbol == '"') {
// Advance to the next character and parse a JSON string at the
// current position. String tokens are prefixed with the sentinel
// `@` character to distinguish them from punctuators.
for (value = "@", Index++; Index < length;) {
symbol = source.charAt(Index);
if (symbol < " ") {
// Unescaped ASCII control characters are not permitted.
abort();
} else if (symbol == "\\") {
// Parse escaped JSON control characters, `"`, `\`, `/`, and
// Unicode escape sequences.
symbol = source.charAt(++Index);
if ('\\"/btnfr'.indexOf(symbol) > -1) {
// Revive escaped control characters.
value += Unescapes[symbol];
Index++;
} else if (symbol == "u") {
// Advance to the first character of the escape sequence.
begin = ++Index;
// Validate the Unicode escape sequence.
for (position = Index + 4; Index < position; Index++) {
symbol = source.charAt(Index);
// A valid sequence comprises four hexdigits that form a
// single hexadecimal value.
if (!(symbol >= "0" && symbol <= "9" || symbol >= "a" && symbol <= "f" || symbol >= "A" && symbol <= "F")) {
// Invalid Unicode escape sequence.
abort();
}
}
// Revive the escaped character.
value += fromCharCode("0x" + source.slice(begin, Index));
} else {
// Invalid escape sequence.
abort();
}
} else {
if (symbol == '"') {
// An unescaped double-quote character marks the end of the
// string.
break;
}
// Append the original character as-is.
value += symbol;
Index++;
}
}
if (source.charAt(Index) == '"') {
Index++;
// Return the revived string.
return value;
}
// Unterminated string.
abort();
} else {
// Parse numbers and literals.
begin = Index;
// Advance the scanner's position past the sign, if one is
// specified.
if (symbol == "-") {
sign = true;
symbol = source.charAt(++Index);
}
// Parse an integer or floating-point value.
if (symbol >= "0" && symbol <= "9") {
// Leading zeroes are interpreted as octal literals.
if (symbol == "0" && (symbol = source.charAt(Index + 1), symbol >= "0" && symbol <= "9")) {
// Illegal octal literal.
abort();
}
sign = false;
// Parse the integer component.
for (; Index < length && (symbol = source.charAt(Index), symbol >= "0" && symbol <= "9"); Index++);
// Floats cannot contain a leading decimal point; however, this
// case is already accounted for by the parser.
if (source.charAt(Index) == ".") {
position = ++Index;
// Parse the decimal component.
for (; position < length && (symbol = source.charAt(position), symbol >= "0" && symbol <= "9"); position++);
if (position == Index) {
// Illegal trailing decimal.
abort();
}
Index = position;
}
// Parse exponents.
symbol = source.charAt(Index);
if (symbol == "e" || symbol == "E") {
// Skip past the sign following the exponent, if one is
// specified.
symbol = source.charAt(++Index);
if (symbol == "+" || symbol == "-") {
Index++;
}
// Parse the exponential component.
for (position = Index; position < length && (symbol = source.charAt(position), symbol >= "0" && symbol <= "9"); position++);
if (position == Index) {
// Illegal empty exponent.
abort();
}
Index = position;
}
// Coerce the parsed value to a JavaScript number.
return +source.slice(begin, Index);
}
// A negative sign may only precede numbers.
if (sign) {
abort();
}
// `true`, `false`, and `null` literals.
if (source.slice(Index, Index + 4) == "true") {
Index += 4;
return true;
} else if (source.slice(Index, Index + 5) == "false") {
Index += 5;
return false;
} else if (source.slice(Index, Index + 4) == "null") {
Index += 4;
return null;
}
// Unrecognized token.
abort();
}
}
// Return the sentinel `$` character if the parser has reached the end
// of the source string.
return "$";
};
// Internal: Parses a JSON `value` token.
get = function (value) {
var results, any, key;
if (value == "$") {
// Unexpected end of input.
abort();
}
if (typeof value == "string") {
if (value.charAt(0) == "@") {
// Remove the sentinel `@` character.
return value.slice(1);
}
// Parse object and array literals.
if (value == "[") {
// Parses a JSON array, returning a new JavaScript array.
results = [];
for (;; any || (any = true)) {
value = lex();
// A closing square bracket marks the end of the array literal.
if (value == "]") {
break;
}
// If the array literal contains elements, the current token
// should be a comma separating the previous element from the
// next.
if (any) {
if (value == ",") {
value = lex();
if (value == "]") {
// Unexpected trailing `,` in array literal.
abort();
}
} else {
// A `,` must separate each array element.
abort();
}
}
// Elisions and leading commas are not permitted.
if (value == ",") {
abort();
}
results.push(get(value));
}
return results;
} else if (value == "{") {
// Parses a JSON object, returning a new JavaScript object.
results = {};
for (;; any || (any = true)) {
value = lex();
// A closing curly brace marks the end of the object literal.
if (value == "}") {
break;
}
// If the object literal contains members, the current token
// should be a comma separator.
if (any) {
if (value == ",") {
value = lex();
if (value == "}") {
// Unexpected trailing `,` in object literal.
abort();
}
} else {
// A `,` must separate each object member.
abort();
}
}
// Leading commas are not permitted, object property names must be
// double-quoted strings, and a `:` must separate each property
// name and value.
if (value == "," || typeof value != "string" || value.charAt(0) != "@" || lex() != ":") {
abort();
}
results[value.slice(1)] = get(lex());
}
return results;
}
// Unexpected token encountered.
abort();
}
return value;
};
// Internal: Updates a traversed object member.
update = function(source, property, callback) {
var element = walk(source, property, callback);
if (element === undef) {
delete source[property];
} else {
source[property] = element;
}
};
// Internal: Recursively traverses a parsed JSON object, invoking the
// `callback` function for each value. This is an implementation of the
// `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
walk = function (source, property, callback) {
var value = source[property], length;
if (typeof value == "object" && value) {
if (getClass.call(value) == "[object Array]") {
for (length = value.length; length--;) {
update(value, length, callback);
}
} else {
// `forEach` can't be used to traverse an array in Opera <= 8.54,
// as `Object#hasOwnProperty` returns `false` for array indices
// (e.g., `![1, 2, 3].hasOwnProperty("0")`).
forEach(value, function (property) {
update(value, property, callback);
});
}
}
return callback.call(source, property, value);
};
// Public: `JSON.parse`. See ES 5.1 section 15.12.2.
JSON3.parse = function (source, callback) {
var result, value;
Index = 0;
Source = source;
result = get(lex());
// If a JSON string contains multiple tokens, it is invalid.
if (lex() != "$") {
abort();
}
// Reset the parser state.
Index = Source = null;
return callback && getClass.call(callback) == "[object Function]" ? walk((value = {}, value[""] = result, value), "", callback) : result;
};
}
}
// Export for asynchronous module loaders.
if (isLoader) {
define(function () {
return JSON3;
});
}
}).call(this);

20
vendor/platform.js/LICENSE.txt vendored Normal file
View File

@@ -0,0 +1,20 @@
Copyright 2011-2013 John-David Dalton <http://allyoucanleet.com/>
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.

98
vendor/platform.js/README.md vendored Normal file
View File

@@ -0,0 +1,98 @@
# Platform.js <sup>v1.0.0</sup>
A platform detection library that works on nearly all JavaScript platforms<sup><a name="fnref1" href="#fn1">1</a></sup>.
## Disclaimer
Platform.js is for informational purposes only and **not** intended as a substitution for [feature detection/inference](http://allyoucanleet.com/post/18087210413/feature-testing-costs#screencast2) checks.
## BestieJS
Platform.js is part of the BestieJS *"Best in Class"* module collection. This means we promote solid browser/environment support, ES5 precedents, unit testing, and plenty of documentation.
## Documentation
The documentation for Platform.js can be viewed here: [/doc/README.md](https://github.com/bestiejs/platform.js/blob/master/doc/README.md#readme)
For a list of upcoming features, check out our [roadmap](https://github.com/bestiejs/platform.js/wiki/Roadmap).
## Support
Platform.js has been tested in at least Adobe AIR 3.1, Chrome 5-21, Firefox 1-14, IE 6-9, Opera 9.25-12, Safari 3-6, Node.js 0.8.6, Narwhal 0.3.2, RingoJS 0.8, and Rhino 1.7RC5.
## Installation and usage
In a browser or Adobe AIR:
```html
<script src="platform.js"></script>
```
Via [npm](http://npmjs.org/):
```bash
npm install platform
```
In [Node.js](http://nodejs.org/) and [RingoJS](http://ringojs.org/):
```js
var platform = require('platform');
```
In [Rhino](http://www.mozilla.org/rhino/):
```js
load('platform.js');
```
In an AMD loader like [RequireJS](http://requirejs.org/):
```js
require({
'paths': {
'platform': 'path/to/platform'
}
},
['platform'], function(platform) {
console.log(platform.name);
});
```
Usage example:
```js
// on IE10 x86 platform preview running in IE7 compatibility mode on Windows 7 64 bit edition
platform.name; // 'IE'
platform.version; // '10.0'
platform.layout; // 'Trident'
platform.os; // 'Windows Server 2008 R2 / 7 x64'
platform.description; // 'IE 10.0 x86 (platform preview; running in IE 7 mode) on Windows Server 2008 R2 / 7 x64'
// or on an iPad
platform.name; // 'Safari'
platform.version; // '5.1'
platform.product; // 'iPad'
platform.manufacturer; // 'Apple'
platform.layout; // 'WebKit'
platform.os; // 'iOS 5.0'
platform.description; // 'Safari 5.1 on Apple iPad (iOS 5.0)'
// or parsing a given UA string
var info = platform.parse('Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7.2; en; rv:2.0) Gecko/20100101 Firefox/4.0 Opera 11.52');
info.name; // 'Opera'
info.version; // '11.52'
info.layout; // 'Presto'
info.os; // 'Mac OS X 10.7.2'
info.description; // 'Opera 11.52 (identifying as Firefox 4.0) on Mac OS X 10.7.2'
```
## Author
* [John-David Dalton](http://allyoucanleet.com/)
[![twitter/jdalton](http://gravatar.com/avatar/299a3d891ff1920b69c364d061007043?s=70)](https://twitter.com/jdalton "Follow @jdalton on Twitter")
## Contributors
* [Mathias Bynens](http://mathiasbynens.be/)
[![twitter/mathias](http://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter")

996
vendor/platform.js/platform.js vendored Normal file
View File

@@ -0,0 +1,996 @@
/*!
* Platform.js v1.0.0 <http://mths.be/platform>
* Copyright 2010-2013 John-David Dalton <http://allyoucanleet.com/>
* Available under MIT license <http://mths.be/mit>
*/
;(function(window) {
'use strict';
/** Backup possible window/global object */
var oldWin = window;
/** Detect free variable `exports` */
var freeExports = typeof exports == 'object' && exports;
/** Detect free variable `global` */
var freeGlobal = typeof global == 'object' && global &&
(global == global.global ? (window = global) : global);
/** Opera regexp */
var reOpera = /Opera/;
/** Used to resolve a value's internal [[Class]] */
var toString = {}.toString;
/** Detect Java environment */
var java = /Java/.test(getClassOf(window.java)) && window.java;
/** A character to represent alpha */
var alpha = java ? 'a' : '\u03b1';
/** A character to represent beta */
var beta = java ? 'b' : '\u03b2';
/** Browser document object */
var doc = window.document || {};
/** Used to check for own properties of an object */
var hasOwnProperty = {}.hasOwnProperty;
/** Browser navigator object */
var nav = window.navigator || {};
/**
* Detect Opera browser
* http://www.howtocreate.co.uk/operaStuff/operaObject.html
* http://dev.opera.com/articles/view/opera-mini-web-content-authoring-guidelines/#operamini
*/
var opera = window.operamini || window.opera;
/** Opera [[Class]] */
var operaClass = reOpera.test(operaClass = getClassOf(opera)) ? operaClass : (opera = null);
/** Possible global object */
var thisBinding = this;
/** Browser user agent string */
var userAgent = nav.userAgent || '';
/*--------------------------------------------------------------------------*/
/**
* Capitalizes a string value.
*
* @private
* @param {String} string The string to capitalize.
* @returns {String} The capitalized string.
*/
function capitalize(string) {
string = String(string);
return string.charAt(0).toUpperCase() + string.slice(1);
}
/**
* An iteration utility for arrays and objects.
*
* @private
* @param {Array|Object} object The object to iterate over.
* @param {Function} callback The function called per iteration.
*/
function each(object, callback) {
var index = -1,
length = object.length;
if (length == length >>> 0) {
while (++index < length) {
callback(object[index], index, object);
}
} else {
forOwn(object, callback);
}
}
/**
* Trim and conditionally capitalize string values.
*
* @private
* @param {String} string The string to format.
* @returns {String} The formatted string.
*/
function format(string) {
string = trim(string);
return /^(?:webOS|i(?:OS|P))/.test(string)
? string
: capitalize(string);
}
/**
* Iterates over an object's own properties, executing the `callback` for each.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} callback The function executed per own property.
*/
function forOwn(object, callback) {
for (var key in object) {
hasKey(object, key) && callback(object[key], key, object);
}
}
/**
* Gets the internal [[Class]] of a value.
*
* @private
* @param {Mixed} value The value.
* @returns {String} The [[Class]].
*/
function getClassOf(value) {
return value == null
? capitalize(value)
: toString.call(value).slice(8, -1);
}
/**
* Checks if an object has the specified key as a direct property.
*
* @private
* @param {Object} object The object to check.
* @param {String} key The key to check for.
* @returns {Boolean} Returns `true` if key is a direct property, else `false`.
*/
function hasKey() {
// lazy define for others (not as accurate)
hasKey = function(object, key) {
var parent = object != null && (object.constructor || Object).prototype;
return !!parent && key in Object(object) && !(key in parent && object[key] === parent[key]);
};
// for modern browsers
if (getClassOf(hasOwnProperty) == 'Function') {
hasKey = function(object, key) {
return object != null && hasOwnProperty.call(object, key);
};
}
// for Safari 2
else if ({}.__proto__ == Object.prototype) {
hasKey = function(object, key) {
var result = false;
if (object != null) {
object = Object(object);
object.__proto__ = [object.__proto__, object.__proto__ = null, result = key in object][0];
}
return result;
};
}
return hasKey.apply(this, arguments);
}
/**
* Host objects can return type values that are different from their actual
* data type. The objects we are concerned with usually return non-primitive
* types of object, function, or unknown.
*
* @private
* @param {Mixed} object The owner of the property.
* @param {String} property The property to check.
* @returns {Boolean} Returns `true` if the property value is a non-primitive, else `false`.
*/
function isHostType(object, property) {
var type = object != null ? typeof object[property] : 'number';
return !/^(?:boolean|number|string|undefined)$/.test(type) &&
(type == 'object' ? !!object[property] : true);
}
/**
* Prepares a string for use in a RegExp constructor by making hyphens and
* spaces optional.
*
* @private
* @param {String} string The string to qualify.
* @returns {String} The qualified string.
*/
function qualify(string) {
return String(string).replace(/([ -])(?!$)/g, '$1?');
}
/**
* A bare-bones` Array#reduce` like utility function.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} callback The function called per iteration.
* @param {Mixed} accumulator Initial value of the accumulator.
* @returns {Mixed} The accumulator.
*/
function reduce(array, callback) {
var accumulator = null;
each(array, function(value, index) {
accumulator = callback(accumulator, value, index, array);
});
return accumulator;
}
/**
* Removes leading and trailing whitespace from a string.
*
* @private
* @param {String} string The string to trim.
* @returns {String} The trimmed string.
*/
function trim(string) {
return String(string).replace(/^ +| +$/g, '');
}
/*--------------------------------------------------------------------------*/
/**
* Creates a new platform object.
*
* @memberOf platform
* @param {String} [ua = navigator.userAgent] The user agent string.
* @returns {Object} A platform object.
*/
function parse(ua) {
ua || (ua = userAgent);
/** Temporary variable used over the script's lifetime */
var data;
/** The CPU architecture */
var arch = ua;
/** Platform description array */
var description = [];
/** Platform alpha/beta indicator */
var prerelease = null;
/** A flag to indicate that environment features should be used to resolve the platform */
var useFeatures = ua == userAgent;
/** The browser/environment version */
var version = useFeatures && opera && typeof opera.version == 'function' && opera.version();
/* Detectable layout engines (order is important) */
var layout = getLayout([
{ 'label': 'WebKit', 'pattern': 'AppleWebKit' },
'iCab',
'Presto',
'NetFront',
'Tasman',
'Trident',
'KHTML',
'Gecko'
]);
/* Detectable browser names (order is important) */
var name = getName([
'Adobe AIR',
'Arora',
'Avant Browser',
'Camino',
'Epiphany',
'Fennec',
'Flock',
'Galeon',
'GreenBrowser',
'iCab',
'Iceweasel',
'Iron',
'K-Meleon',
'Konqueror',
'Lunascape',
'Maxthon',
'Midori',
'Nook Browser',
'PhantomJS',
'Raven',
'Rekonq',
'RockMelt',
'SeaMonkey',
{ 'label': 'Silk', 'pattern': '(?:Cloud9|Silk-Accelerated)' },
'Sleipnir',
'SlimBrowser',
'Sunrise',
'Swiftfox',
'WebPositive',
'Opera Mini',
'Opera',
'Chrome',
{ 'label': 'Chrome Mobile', 'pattern': '(?:CriOS|CrMo)' },
{ 'label': 'Firefox', 'pattern': '(?:Firefox|Minefield)' },
{ 'label': 'IE', 'pattern': 'MSIE' },
'Safari'
]);
/* Detectable products (order is important) */
var product = getProduct([
'BlackBerry',
{ 'label': 'Galaxy S', 'pattern': 'GT-I9000' },
{ 'label': 'Galaxy S2', 'pattern': 'GT-I9100' },
'Google TV',
'iPad',
'iPod',
'iPhone',
'Kindle',
{ 'label': 'Kindle Fire', 'pattern': '(?:Cloud9|Silk-Accelerated)' },
'Nook',
'PlayBook',
'PlayStation Vita',
'TouchPad',
'Transformer',
'Xoom'
]);
/* Detectable manufacturers */
var manufacturer = getManufacturer({
'Apple': { 'iPad': 1, 'iPhone': 1, 'iPod': 1 },
'Amazon': { 'Kindle': 1, 'Kindle Fire': 1 },
'Asus': { 'Transformer': 1 },
'Barnes & Noble': { 'Nook': 1 },
'BlackBerry': { 'PlayBook': 1 },
'Google': { 'Google TV': 1 },
'HP': { 'TouchPad': 1 },
'LG': { },
'Motorola': { 'Xoom': 1 },
'Nokia': { },
'Samsung': { 'Galaxy S': 1, 'Galaxy S2': 1 },
'Sony': { 'PlayStation Vita': 1 }
});
/* Detectable OSes (order is important) */
var os = getOS([
'Android',
'CentOS',
'Debian',
'Fedora',
'FreeBSD',
'Gentoo',
'Haiku',
'Kubuntu',
'Linux Mint',
'Red Hat',
'SuSE',
'Ubuntu',
'Xubuntu',
'Cygwin',
'Symbian OS',
'hpwOS',
'webOS ',
'webOS',
'Tablet OS',
'Linux',
'Mac OS X',
'Macintosh',
'Mac',
'Windows 98;',
'Windows '
]);
/*------------------------------------------------------------------------*/
/**
* Picks the layout engine from an array of guesses.
*
* @private
* @param {Array} guesses An array of guesses.
* @returns {String|Null} The detected layout engine.
*/
function getLayout(guesses) {
return reduce(guesses, function(result, guess) {
return result || RegExp('\\b' + (
guess.pattern || qualify(guess)
) + '\\b', 'i').exec(ua) && (guess.label || guess);
});
}
/**
* Picks the manufacturer from an array of guesses.
*
* @private
* @param {Array} guesses An array of guesses.
* @returns {String|Null} The detected manufacturer.
*/
function getManufacturer(guesses) {
return reduce(guesses, function(result, value, key) {
// lookup the manufacturer by product or scan the UA for the manufacturer
return result || (
value[product] ||
value[0/*Opera 9.25 fix*/, /^[a-z]+(?: +[a-z]+\b)*/i.exec(product)] ||
RegExp('\\b' + (key.pattern || qualify(key)) + '(?:\\b|\\w*\\d)', 'i').exec(ua)
) && (key.label || key);
});
}
/**
* Picks the browser name from an array of guesses.
*
* @private
* @param {Array} guesses An array of guesses.
* @returns {String|Null} The detected browser name.
*/
function getName(guesses) {
return reduce(guesses, function(result, guess) {
return result || RegExp('\\b' + (
guess.pattern || qualify(guess)
) + '\\b', 'i').exec(ua) && (guess.label || guess);
});
}
/**
* Picks the OS name from an array of guesses.
*
* @private
* @param {Array} guesses An array of guesses.
* @returns {String|Null} The detected OS name.
*/
function getOS(guesses) {
return reduce(guesses, function(result, guess) {
var pattern = guess.pattern || qualify(guess);
if (!result && (result =
RegExp('\\b' + pattern + '(?:/[\\d.]+|[ \\w.]*)', 'i').exec(ua))) {
// platform tokens defined at
// http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx
// http://web.archive.org/web/20081122053950/http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx
data = {
'6.2': '8',
'6.1': 'Server 2008 R2 / 7',
'6.0': 'Server 2008 / Vista',
'5.2': 'Server 2003 / XP 64-bit',
'5.1': 'XP',
'5.01': '2000 SP1',
'5.0': '2000',
'4.0': 'NT',
'4.90': 'ME'
};
// detect Windows version from platform tokens
if (/^Win/i.test(result) &&
(data = data[0/*Opera 9.25 fix*/, /[\d.]+$/.exec(result)])) {
result = 'Windows ' + data;
}
// correct character case and cleanup
result = format(String(result)
.replace(RegExp(pattern, 'i'), guess.label || guess)
.replace(/ ce$/i, ' CE')
.replace(/hpw/i, 'web')
.replace(/Macintosh/, 'Mac OS')
.replace(/_PowerPC/i, ' OS')
.replace(/(OS X) [^ \d]+/i, '$1')
.replace(/\/(\d)/, ' $1')
.replace(/_/g, '.')
.replace(/(?: BePC|[ .]*fc[ \d.]+)$/i, '')
.replace(/x86\.64/gi, 'x86_64')
.split(' on ')[0]);
}
return result;
});
}
/**
* Picks the product name from an array of guesses.
*
* @private
* @param {Array} guesses An array of guesses.
* @returns {String|Null} The detected product name.
*/
function getProduct(guesses) {
return reduce(guesses, function(result, guess) {
var pattern = guess.pattern || qualify(guess);
if (!result && (result =
RegExp('\\b' + pattern + ' *\\d+[.\\w_]*', 'i').exec(ua) ||
RegExp('\\b' + pattern + '(?:; *(?:[a-z]+[_-])?[a-z]+\\d+|[^ ();-]*)', 'i').exec(ua)
)) {
// split by forward slash and append product version if needed
if ((result = String(guess.label || result).split('/'))[1] && !/[\d.]+/.test(result[0])) {
result[0] += ' ' + result[1];
}
// correct character case and cleanup
guess = guess.label || guess;
result = format(result[0]
.replace(RegExp(pattern, 'i'), guess)
.replace(RegExp('; *(?:' + guess + '[_-])?', 'i'), ' ')
.replace(RegExp('(' + guess + ')(\\w)', 'i'), '$1 $2'));
}
return result;
});
}
/**
* Resolves the version using an array of UA patterns.
*
* @private
* @param {Array} patterns An array of UA patterns.
* @returns {String|Null} The detected version.
*/
function getVersion(patterns) {
return reduce(patterns, function(result, pattern) {
return result || (RegExp(pattern +
'(?:-[\\d.]+/|(?: for [\\w-]+)?[ /-])([\\d.]+[^ ();/_-]*)', 'i').exec(ua) || 0)[1] || null;
});
}
/*------------------------------------------------------------------------*/
/**
* Returns `platform.description` when the platform object is coerced to a string.
*
* @name toString
* @memberOf platform
* @returns {String} Returns `platform.description` if available, else an empty string.
*/
function toStringPlatform() {
return this.description || '';
}
/*------------------------------------------------------------------------*/
// convert layout to an array so we can add extra details
layout && (layout = [layout]);
// detect product names that contain their manufacturer's name
if (manufacturer && !product) {
product = getProduct([manufacturer]);
}
// clean up Google TV
if ((data = /Google TV/.exec(product))) {
product = data[0];
}
// detect simulators
if (/\bSimulator\b/i.test(ua)) {
product = (product ? product + ' ' : '') + 'Simulator';
}
// detect iOS
if (/^iP/.test(product)) {
name || (name = 'Safari');
os = 'iOS' + ((data = / OS ([\d_]+)/i.exec(ua))
? ' ' + data[1].replace(/_/g, '.')
: '');
}
// detect Kubuntu
else if (name == 'Konqueror' && !/buntu/i.test(os)) {
os = 'Kubuntu';
}
// detect Android browsers
else if (manufacturer && manufacturer != 'Google' &&
/Chrome|Vita/.test(name + ';' + product)) {
name = 'Android Browser';
os = /Android/.test(os) ? os : 'Android';
}
// detect false positives for Firefox/Safari
else if (!name || (data = !/\bMinefield\b/i.test(ua) && /Firefox|Safari/.exec(name))) {
// escape the `/` for Firefox 1
if (name && !product && /[\/,]|^[^(]+?\)/.test(ua.slice(ua.indexOf(data + '/') + 8))) {
// clear name of false positives
name = null;
}
// reassign a generic name
if ((data = product || manufacturer || os) &&
(product || manufacturer || /Android|Symbian OS|Tablet OS|webOS/.test(os))) {
name = /[a-z]+(?: Hat)?/i.exec(/Android/.test(os) ? os : data) + ' Browser';
}
}
// detect non-Opera versions (order is important)
if (!version) {
version = getVersion([
'(?:Cloud9|CriOS|CrMo|Opera ?Mini|Raven|Silk(?!/[\\d.]+$))',
'Version',
qualify(name),
'(?:Firefox|Minefield|NetFront)'
]);
}
// detect stubborn layout engines
if (layout == 'iCab' && parseFloat(version) > 3) {
layout = ['WebKit'];
} else if (data =
/Opera/.test(name) && 'Presto' ||
/\b(?:Midori|Nook|Safari)\b/i.test(ua) && 'WebKit' ||
!layout && /\bMSIE\b/i.test(ua) && (/^Mac/.test(os) ? 'Tasman' : 'Trident')) {
layout = [data];
}
// leverage environment features
if (useFeatures) {
// detect server-side environments
// Rhino has a global function while others have a global object
if (isHostType(window, 'global')) {
if (java) {
data = java.lang.System;
arch = data.getProperty('os.arch');
os = os || data.getProperty('os.name') + ' ' + data.getProperty('os.version');
}
if (typeof exports == 'object' && exports) {
// if `thisBinding` is the [ModuleScope]
if (thisBinding == oldWin && typeof system == 'object' && (data = [system])[0]) {
os || (os = data[0].os || null);
try {
data[1] = require('ringo/engine').version;
version = data[1].join('.');
name = 'RingoJS';
} catch(e) {
if (data[0].global == freeGlobal) {
name = 'Narwhal';
}
}
} else if (typeof process == 'object' && (data = process)) {
name = 'Node.js';
arch = data.arch;
os = data.platform;
version = /[\d.]+/.exec(data.version)[0];
}
} else if (getClassOf(window.environment) == 'Environment') {
name = 'Rhino';
}
}
// detect Adobe AIR
else if (getClassOf(data = window.runtime) == 'ScriptBridgingProxyObject') {
name = 'Adobe AIR';
os = data.flash.system.Capabilities.os;
}
// detect PhantomJS
else if (getClassOf(data = window.phantom) == 'RuntimeObject') {
name = 'PhantomJS';
version = (data = data.version || null) && (data.major + '.' + data.minor + '.' + data.patch);
}
// detect IE compatibility modes
else if (typeof doc.documentMode == 'number' && (data = /\bTrident\/(\d+)/i.exec(ua))) {
// we're in compatibility mode when the Trident version + 4 doesn't
// equal the document mode
version = [version, doc.documentMode];
if ((data = +data[1] + 4) != version[1]) {
description.push('IE ' + version[1] + ' mode');
layout[1] = '';
version[1] = data;
}
version = name == 'IE' ? String(version[1].toFixed(1)) : version[0];
}
os = os && format(os);
}
// detect prerelease phases
if (version && (data =
/(?:[ab]|dp|pre|[ab]\d+pre)(?:\d+\+?)?$/i.exec(version) ||
/(?:alpha|beta)(?: ?\d)?/i.exec(ua + ';' + (useFeatures && nav.appMinorVersion)) ||
/\bMinefield\b/i.test(ua) && 'a')) {
prerelease = /b/i.test(data) ? 'beta' : 'alpha';
version = version.replace(RegExp(data + '\\+?$'), '') +
(prerelease == 'beta' ? beta : alpha) + (/\d+\+?/.exec(data) || '');
}
// rename code name "Fennec"
if (name == 'Fennec') {
name = 'Firefox Mobile';
}
// obscure Maxthon's unreliable version
else if (name == 'Maxthon' && version) {
version = version.replace(/\.[\d.]+/, '.x');
}
// detect Silk desktop/accelerated modes
else if (name == 'Silk') {
if (!/Mobi/i.test(ua)) {
os = 'Android';
description.unshift('desktop mode');
}
if (/Accelerated *= *true/i.test(ua)) {
description.unshift('accelerated');
}
}
// detect Windows Phone desktop mode
else if (name == 'IE' && (data = (/; *(?:XBLWP|ZuneWP)(\d+)/i.exec(ua) || 0)[1])) {
name += ' Mobile';
os = 'Windows Phone OS ' + data + '.x';
description.unshift('desktop mode');
}
// add mobile postfix
else if ((name == 'IE' || name && !product && !/Browser|Mobi/.test(name)) &&
(os == 'Windows CE' || /Mobi/i.test(ua))) {
name += ' Mobile';
}
// detect IE platform preview
else if (name == 'IE' && useFeatures && typeof external == 'object' && !external) {
description.unshift('platform preview');
}
// detect BlackBerry OS version
// http://docs.blackberry.com/en/developers/deliverables/18169/HTTP_headers_sent_by_BB_Browser_1234911_11.jsp
else if (/BlackBerry/.test(product) && (data =
(RegExp(product.replace(/ +/g, ' *') + '/([.\\d]+)', 'i').exec(ua) || 0)[1] ||
version)) {
os = 'Device Software ' + data;
version = null;
}
// detect Opera identifying/masking itself as another browser
// http://www.opera.com/support/kb/view/843/
else if (this != forOwn && (
(useFeatures && opera) ||
(/Opera/.test(name) && /\b(?:MSIE|Firefox)\b/i.test(ua)) ||
(name == 'Firefox' && /OS X (?:\d+\.){2,}/.test(os)) ||
(name == 'IE' && (
(os && !/^Win/.test(os) && version > 5.5) ||
/Windows XP/.test(os) && version > 8 ||
version == 8 && !/Trident/.test(ua)
))
) && !reOpera.test(data = parse.call(forOwn, ua.replace(reOpera, '') + ';')) && data.name) {
// when "indentifying", the UA contains both Opera and the other browser's name
data = 'ing as ' + data.name + ((data = data.version) ? ' ' + data : '');
if (reOpera.test(name)) {
if (/IE/.test(data) && os == 'Mac OS') {
os = null;
}
data = 'identify' + data;
}
// when "masking", the UA contains only the other browser's name
else {
data = 'mask' + data;
if (operaClass) {
name = format(operaClass.replace(/([a-z])([A-Z])/g, '$1 $2'));
} else {
name = 'Opera';
}
if (/IE/.test(data)) {
os = null;
}
if (!useFeatures) {
version = null;
}
}
layout = ['Presto'];
description.push(data);
}
// detect WebKit Nightly and approximate Chrome/Safari versions
if ((data = (/\bAppleWebKit\/([\d.]+\+?)/i.exec(ua) || 0)[1])) {
// correct build for numeric comparison
// (e.g. "532.5" becomes "532.05")
data = [parseFloat(data.replace(/\.(\d)$/, '.0$1')), data];
// nightly builds are postfixed with a `+`
if (name == 'Safari' && data[1].slice(-1) == '+') {
name = 'WebKit Nightly';
prerelease = 'alpha';
version = data[1].slice(0, -1);
}
// clear incorrect browser versions
else if (version == data[1] ||
version == (/\bSafari\/([\d.]+\+?)/i.exec(ua) || 0)[1]) {
version = null;
}
// use the full Chrome version when available
data = [data[0], (/\bChrome\/([\d.]+)/i.exec(ua) || 0)[1]];
// detect JavaScriptCore
// http://stackoverflow.com/questions/6768474/how-can-i-detect-which-javascript-engine-v8-or-jsc-is-used-at-runtime-in-androi
if (!useFeatures || (/internal|\n/i.test(toString.toString()) && !data[1])) {
layout[1] = 'like Safari';
data = (data = data[0], data < 400 ? 1 : data < 500 ? 2 : data < 526 ? 3 : data < 533 ? 4 : data < 534 ? '4+' : data < 535 ? 5 : '5');
} else {
layout[1] = 'like Chrome';
data = data[1] || (data = data[0], data < 530 ? 1 : data < 532 ? 2 : data < 532.05 ? 3 : data < 533 ? 4 : data < 534.03 ? 5 : data < 534.07 ? 6 : data < 534.10 ? 7 : data < 534.13 ? 8 : data < 534.16 ? 9 : data < 534.24 ? 10 : data < 534.30 ? 11 : data < 535.01 ? 12 : data < 535.02 ? '13+' : data < 535.07 ? 15 : data < 535.11 ? 16 : data < 535.19 ? 17 : data < 536.05 ? 18 : data < 536.10 ? 19 : data < 537.01 ? 20 : '21');
}
// add the postfix of ".x" or "+" for approximate versions
layout[1] += ' ' + (data += typeof data == 'number' ? '.x' : /[.+]/.test(data) ? '' : '+');
// obscure version for some Safari 1-2 releases
if (name == 'Safari' && (!version || parseInt(version) > 45)) {
version = data;
}
}
// detect Opera desktop modes
if (name == 'Opera' && (data = /(?:zbov|zvav)$/.exec(os))) {
name += ' ';
description.unshift('desktop mode');
if (data == 'zvav') {
name += 'Mini';
version = null;
} else {
name += 'Mobile';
}
}
// detect Chrome desktop mode
else if (name == 'Safari' && /Chrome/.exec(layout[1])) {
description.unshift('desktop mode');
name = 'Chrome Mobile';
version = null;
if (/Mac OS X/.test(os)) {
manufacturer = 'Apple';
os = 'iOS 4.3+';
} else {
os = null;
}
}
// strip incorrect OS versions
if (version && version.indexOf(data = /[\d.]+$/.exec(os)) == 0 &&
ua.indexOf('/' + data + '-') > -1) {
os = trim(os.replace(data, ''));
}
// add layout engine
if (layout && !/Avant|Nook/.test(name) && (
/Browser|Lunascape|Maxthon/.test(name) ||
/^(?:Adobe|Arora|Midori|Phantom|Rekonq|Rock|Sleipnir|Web)/.test(name) && layout[1])) {
// don't add layout details to description if they are falsey
(data = layout[layout.length - 1]) && description.push(data);
}
// combine contextual information
if (description.length) {
description = ['(' + description.join('; ') + ')'];
}
// append manufacturer
if (manufacturer && product && product.indexOf(manufacturer) < 0) {
description.push('on ' + manufacturer);
}
// append product
if (product) {
description.push((/^on /.test(description[description.length -1]) ? '' : 'on ') + product);
}
// parse OS into an object
if (os) {
data = / ([\d.+]+)$/.exec(os);
os = {
'architecture': 32,
'family': data ? os.replace(data[0], '') : os,
'version': data ? data[1] : null,
'toString': function() {
var version = this.version;
return this.family + (version ? ' ' + version : '') + (this.architecture == 64 ? ' 64-bit' : '');
}
};
}
// add browser/OS architecture
if ((data = /\b(?:AMD|IA|Win|WOW|x86_|x)64\b/i.exec(arch)) && !/\bi686\b/i.test(arch)) {
if (os) {
os.architecture = 64;
os.family = os.family.replace(RegExp(' *' + data), '');
}
if (name && (/WOW64/i.test(ua) ||
(useFeatures && /\w(?:86|32)$/.test(nav.cpuClass || nav.platform)))) {
description.unshift('32-bit');
}
}
ua || (ua = null);
/*------------------------------------------------------------------------*/
/**
* The platform object.
*
* @name platform
* @type Object
*/
return {
/**
* The browser/environment version.
*
* @memberOf platform
* @type String|Null
*/
'version': name && version && (description.unshift(version), version),
/**
* The name of the browser/environment.
*
* @memberOf platform
* @type String|Null
*/
'name': name && (description.unshift(name), name),
/**
* The name of the operating system.
*
* @memberOf platform
* @type Object
*/
'os': os
? (name &&
!(os == String(os).split(' ')[0] && (os == name.split(' ')[0] || product)) &&
description.push(product ? '(' + os + ')' : 'on ' + os), os)
: {
/**
* The CPU architecture the OS is built for.
*
* @memberOf platform.os
* @type Number|Null
*/
'architecture': null,
/**
* The family of the OS.
*
* @memberOf platform.os
* @type String|Null
*/
'family': null,
/**
* The version of the OS.
*
* @memberOf platform.os
* @type String|Null
*/
'version': null,
/**
* Returns the OS string.
*
* @memberOf platform.os
* @returns {String} The OS string.
*/
'toString': function() { return 'null'; }
},
/**
* The platform description.
*
* @memberOf platform
* @type String|Null
*/
'description': description.length ? description.join(' ') : ua,
/**
* The name of the browser layout engine.
*
* @memberOf platform
* @type String|Null
*/
'layout': layout && layout[0],
/**
* The name of the product's manufacturer.
*
* @memberOf platform
* @type String|Null
*/
'manufacturer': manufacturer,
/**
* The alpha/beta release indicator.
*
* @memberOf platform
* @type String|Null
*/
'prerelease': prerelease,
/**
* The name of the product hosting the browser.
*
* @memberOf platform
* @type String|Null
*/
'product': product,
/**
* The browser's user agent string.
*
* @memberOf platform
* @type String|Null
*/
'ua': ua,
// parses a user agent string into a platform object
'parse': parse,
// returns the platform description
'toString': toStringPlatform
};
}
/*--------------------------------------------------------------------------*/
// expose platform
// some AMD build optimizers, like r.js, check for specific condition patterns like the following:
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
// define as an anonymous module so, through path mapping, it can be aliased
define(function() {
return parse();
});
}
// check for `exports` after `define` in case a build optimizer adds an `exports` object
else if (freeExports) {
// in Narwhal, Node.js, or RingoJS
forOwn(parse(), function(value, key) {
freeExports[key] = value;
});
}
// in a browser or Rhino
else {
// use square bracket notation so Closure Compiler won't munge `platform`
// http://code.google.com/closure/compiler/docs/api-tutorial3.html#export
window['platform'] = parse();
}
}(this));

20
vendor/qunit-clib/LICENSE.txt vendored Normal file
View File

@@ -0,0 +1,20 @@
Copyright 2011-2013 John-David Dalton <http://allyoucanleet.com/>
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.

58
vendor/qunit-clib/README.md vendored Normal file
View File

@@ -0,0 +1,58 @@
# QUnit CLIB <sup>v1.2.0</sup>
## command-line interface boilerplate
QUnit CLIB helps extend QUnit's CLI support to many common CLI environments.
## Screenshot
![QUnit CLIB brings QUnit to your favorite shell.](http://i.imgur.com/jpu9l.png)
## Support
QUnit CLIB has been tested in at least Node.js 0.4.8-0.8.19, Narwhal v0.3.2, PhantomJS 1.8.1, RingoJS v0.9, and Rhino v1.7RC5.
## Usage
```js
(function(window) {
// use a single "load" function
var load = typeof require == 'function' ? require : window.load;
// load QUnit and CLIB if needed
var QUnit =
window.QUnit || (
window.addEventListener || (window.addEventListener = Function.prototype),
window.setTimeout || (window.setTimeout = Function.prototype),
window.QUnit = load('path/to/qunit.js') || window.QUnit,
load('path/to/qunit-clib.js'),
window.addEventListener === Function.prototype && delete window.addEventListener,
window.QUnit
);
// explicitly call `QUnit.module()` instead of `module()`
// in case we are in a CLI environment
QUnit.module('A Test Module');
test('A Test', function() {
// ...
});
// must call `QUnit.start()` if using QUnit < 1.3.0 with Node.js or any
// version of QUnit with Narwhal, PhantomJS, Rhino, or RingoJS
if (!window.document) {
QUnit.start();
}
}(typeof global == 'object' && global || this));
```
## Footnotes
1. QUnit v1.3.0 does not work with Narwhal or Ringo < v0.8.0
2. Rhino v1.7RC4 does not support timeout fallbacks `clearTimeout` and `setTimeout`
## Author
* [John-David Dalton](http://allyoucanleet.com/)
[![twitter/jdalton](http://gravatar.com/avatar/299a3d891ff1920b69c364d061007043?s=70)](https://twitter.com/jdalton "Follow @jdalton on Twitter")

269
vendor/qunit-clib/qunit-clib.js vendored Normal file
View File

@@ -0,0 +1,269 @@
/*!
* QUnit CLI Boilerplate v1.2.0
* Copyright 2011-2012 John-David Dalton <http://allyoucanleet.com/>
* Based on a gist by Jörn Zaefferer <https://gist.github.com/722381>
* Available under MIT license <http://mths.be/mit>
*/
;(function(window) {
'use strict';
/**
* Timeout fallbacks based on the work of Andrea Giammarchi and Weston C.
* https://github.com/WebReflection/wru/blob/master/src/rhinoTimers.js
* http://stackoverflow.com/questions/2261705/how-to-run-a-javascript-function-asynchronously-without-using-settimeout
*/
(function() {
/**
* Schedules timer-based callbacks.
*
* @private
* @param {Function|String} fn The function to call.
* @oaram {Number} delay The number of milliseconds to delay the `fn` call.
* @param [arg1, arg2, ...] Arguments to invoke `fn` with.
* @param {Boolean} repeated A flag to specify whether `fn` is called repeatedly.
* @returns {Number} The the ID of the timeout.
*/
function schedule(fn, delay, args, repeated) {
// Rhino 1.7RC4 will error assigning `task` below
// https://bugzilla.mozilla.org/show_bug.cgi?id=775566
var task = ids[++counter] = new JavaAdapter(java.util.TimerTask, {
'run': function() {
fn.apply(window, args);
}
});
// support non-functions
if (typeof fn != 'function') {
fn = (function(code) {
code = String(code);
return function() { eval(code); };
}(fn));
}
// used by setInterval
if (repeated) {
timer.schedule(task, delay, delay);
}
// used by setTimeout
else {
timer.schedule(task, delay);
}
return counter;
}
/**
* Clears the delay set by `setInterval` or `setTimeout`.
*
* @memberOf window
* @param {Number} id The ID of the timeout to be cleared.
*/
function clearTimer(id) {
if (ids[id]) {
ids[id].cancel();
timer.purge();
delete ids[id];
}
}
/**
* Executes a code snippet or function repeatedly, with a delay between each call.
*
* @memberOf window
* @param {Function|String} fn The function to call or string to evaluate.
* @oaram {Number} delay The number of milliseconds to delay each `fn` call.
* @param [arg1, arg2, ...] Arguments to invoke `fn` with.
* @returns {Number} The the ID of the timeout.
*/
function setInterval(fn, delay) {
return schedule(fn, delay, slice.call(arguments, 2), true);
}
/**
* Executes a code snippet or a function after specified delay.
*
* @memberOf window
* @param {Function|String} fn The function to call or string to evaluate.
* @oaram {Number} delay The number of milliseconds to delay the `fn` call.
* @param [arg1, arg2, ...] Arguments to invoke `fn` with.
* @returns {Number} The the ID of the timeout.
*/
function setTimeout(fn, delay) {
return schedule(fn, delay, slice.call(arguments, 2));
}
try {
var counter = 0,
ids = {},
slice = Array.prototype.slice,
timer = new java.util.Timer;
window.clearInterval =
window.clearTimeout = clearTimer;
window.setInterval = setInterval;
window.setTimeout = setTimeout;
} catch(e) { }
}());
/*--------------------------------------------------------------------------*/
(function() {
/** Used as a horizontal rule in console output */
var hr = '----------------------------------------';
/** Shorten `window.QUnit.QUnit` to `window.QUnit` */
window.QUnit && (QUnit = QUnit.QUnit || QUnit);
/**
* A logging callback triggered when all testing is completed.
*
* @memberOf QUnit
* @param {Object} details An object with properties `failed`, `passed`, `runtime`, and `total`.
*/
QUnit.done(function() {
var ran;
return function(details) {
// stop `asyncTest()` from erroneously calling `done()` twice in
// environments w/o timeouts
if (ran) {
return;
}
ran = true;
console.log(hr);
console.log(' PASS: ' + details.passed + ' FAIL: ' + details.failed + ' TOTAL: ' + details.total);
console.log(' Finished in ' + details.runtime + ' milliseconds.');
console.log(hr);
// exit out of Rhino
try {
quit();
} catch(e) { }
// exit out of Node.js or PhantomJS
try {
var process = window.process || window.phantom;
if (details.failed) {
console.error('Error: ' + details.failed + ' of ' + details.total + ' tests failed.');
process.exit(1);
} else {
process.exit(0);
}
} catch(e) { }
};
}());
/**
* A logging callback triggered after every assertion.
*
* @memberOf QUnit
* @param {Object} details An object with properties `actual`, `expected`, `message`, and `result`.
*/
QUnit.log(function(details) {
var expected = details.expected,
result = details.result,
type = typeof expected != 'undefined' ? 'EQ' : 'OK';
var assertion = [
result ? 'PASS' : 'FAIL',
type,
details.message || 'ok'
];
if (!result && type == 'EQ') {
assertion.push('Expected: ' + expected + ', Actual: ' + details.actual);
}
QUnit.config.testStats.assertions.push(assertion.join(' | '));
});
/**
* A logging callback triggered at the start of every test module.
*
* @memberOf QUnit
* @param {Object} details An object with property `name`.
*/
QUnit.moduleStart(function(details) {
console.log(hr);
console.log(details.name);
console.log(hr);
});
/**
* Converts an object into a string representation.
*
* @memberOf QUnit
* @type Function
* @param {Object} object The object to stringify.
* @returns {String} The result string.
*/
QUnit.jsDump.parsers.object = (function() {
var func = QUnit.jsDump.parsers.object;
return function(object) {
// fork to support Rhino's error objects
if (typeof object.rhinoException == 'object') {
return object.name +
' { message: "' + object.message +
'", fileName: "' + object.fileName +
'", lineNumber: ' + object.lineNumber + ' }';
}
return func(object);
};
}());
/**
* A logging callback triggered after a test is completed.
*
* @memberOf QUnit
* @param {Object} details An object with properties `failed`, `name`, `passed`, and `total`.
*/
QUnit.testDone(function(details) {
var assertions = QUnit.config.testStats.assertions,
testName = details.name;
if (details.failed > 0) {
console.log(' FAIL - '+ testName);
assertions.forEach(function(value) {
console.log(' ' + value);
});
}
else {
console.log(' PASS - ' + testName);
}
assertions.length = 0;
});
/**
* An object used to hold information about the current running test.
*
* @memberOf QUnit.config
* @type Object
*/
QUnit.config.testStats = {
/**
* An array of test summaries (pipe separated).
*
* @memberOf QUnit.config.testStats
* @type Array
*/
'assertions': []
};
}());
/*--------------------------------------------------------------------------*/
// expose shortcuts
// exclude `module` because some environments have it as a built-in object
('asyncTest deepEqual equal equals expect notDeepEqual notEqual notStrictEqual ' +
'ok raises same start stop strictEqual test throws').replace(/\S+/g, function(methodName) {
window[methodName] = QUnit[methodName];
});
// add `console.log()` support for Narwhal, Rhino, and RingoJS
if (!window.console && window.print) {
window.console = { 'log': window.print };
}
// must call `QUnit.start()` in the test file if using QUnit < 1.3.0 with
// Node.js or any version of QUnit with Narwhal, PhantomJS, Rhino, or RingoJS
QUnit.init();
}(typeof global == 'object' && global || this));

62
vendor/qunit/README.md vendored Normal file
View File

@@ -0,0 +1,62 @@
[QUnit](http://qunitjs.com) - A JavaScript Unit Testing framework.
================================
QUnit is a powerful, easy-to-use, JavaScript test suite. It's used by the jQuery
project to test its code and plugins but is capable of testing any generic
JavaScript code (and even capable of testing JavaScript code on the server-side).
QUnit is especially useful for regression testing: Whenever a bug is reported,
write a test that asserts the existence of that particular bug. Then fix it and
commit both. Every time you work on the code again, run the tests. If the bug
comes up again - a regression - you'll spot it immediately and know how to fix
it, because you know what code you just changed.
Having good unit test coverage makes safe refactoring easy and cheap. You can
run the tests after each small refactoring step and always know what change
broke something.
QUnit is similar to other unit testing frameworks like JUnit, but makes use of
the features JavaScript provides and helps with testing code in the browser, e.g.
with its stop/start facilities for testing asynchronous code.
If you are interested in helping developing QUnit, you are in the right place.
For related discussions, visit the
[QUnit and Testing forum](http://forum.jquery.com/qunit-and-testing).
Development
-----------
To submit patches, fork the repository, create a branch for the change. Then implement
the change, run `grunt` to lint and test it, then commit, push and create a pull request.
Include some background for the change in the commit message and `Fixes #nnn`, referring
to the issue number you're addressing.
To run `grunt`, you need `node` and `npm`, then `npm install grunt -g`. That gives you a global
grunt binary. For additional grunt tasks, also run `npm install`.
Releases
--------
Install git-extras and run `git changelog` to update History.md.
Update qunit/qunit.js|css and package.json to the release version, commit and
tag, update them again to the next version, commit and push commits and tags
(`git push --tags origin master`).
Put the 'v' in front of the tag, e.g. `v1.8.0`. Clean up the changelog, removing merge commits
or whitespace cleanups.
To upload to code.jquery.com (replace $version accordingly), ssh to code.origin.jquery.com:
cp qunit/qunit.js /var/www/html/code.jquery.com/qunit/qunit-$version.js
cp qunit/qunit.css /var/www/html/code.jquery.com/qunit/qunit-$version.css
Then update /var/www/html/code.jquery.com/index.html and purge it with:
curl -s http://code.origin.jquery.com/?reload
Update web-base-template to link to those files for qunitjs.com.
Publish to npm via
npm publish

244
vendor/qunit/qunit/qunit.css vendored Normal file
View File

@@ -0,0 +1,244 @@
/**
* QUnit v1.11.0 - A JavaScript Unit Testing Framework
*
* http://qunitjs.com
*
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
/** Font Family and Sizes */
#qunit-tests, #qunit-header, #qunit-banner, #qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult {
font-family: "Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial, sans-serif;
}
#qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult, #qunit-tests li { font-size: small; }
#qunit-tests { font-size: smaller; }
/** Resets */
#qunit-tests, #qunit-header, #qunit-banner, #qunit-userAgent, #qunit-testresult, #qunit-modulefilter {
margin: 0;
padding: 0;
}
/** Header */
#qunit-header {
padding: 0.5em 0 0.5em 1em;
color: #8699a4;
background-color: #0d3349;
font-size: 1.5em;
line-height: 1em;
font-weight: normal;
border-radius: 5px 5px 0 0;
-moz-border-radius: 5px 5px 0 0;
-webkit-border-top-right-radius: 5px;
-webkit-border-top-left-radius: 5px;
}
#qunit-header a {
text-decoration: none;
color: #c2ccd1;
}
#qunit-header a:hover,
#qunit-header a:focus {
color: #fff;
}
#qunit-testrunner-toolbar label {
display: inline-block;
padding: 0 .5em 0 .1em;
}
#qunit-banner {
height: 5px;
}
#qunit-testrunner-toolbar {
padding: 0.5em 0 0.5em 2em;
color: #5E740B;
background-color: #eee;
overflow: hidden;
}
#qunit-userAgent {
padding: 0.5em 0 0.5em 2.5em;
background-color: #2b81af;
color: #fff;
text-shadow: rgba(0, 0, 0, 0.5) 2px 2px 1px;
}
#qunit-modulefilter-container {
float: right;
}
/** Tests: Pass/Fail */
#qunit-tests {
list-style-position: inside;
}
#qunit-tests li {
padding: 0.4em 0.5em 0.4em 2.5em;
border-bottom: 1px solid #fff;
list-style-position: inside;
}
#qunit-tests.hidepass li.pass, #qunit-tests.hidepass li.running {
display: none;
}
#qunit-tests li strong {
cursor: pointer;
}
#qunit-tests li a {
padding: 0.5em;
color: #c2ccd1;
text-decoration: none;
}
#qunit-tests li a:hover,
#qunit-tests li a:focus {
color: #000;
}
#qunit-tests li .runtime {
float: right;
font-size: smaller;
}
.qunit-assert-list {
margin-top: 0.5em;
padding: 0.5em;
background-color: #fff;
border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
}
.qunit-collapsed {
display: none;
}
#qunit-tests table {
border-collapse: collapse;
margin-top: .2em;
}
#qunit-tests th {
text-align: right;
vertical-align: top;
padding: 0 .5em 0 0;
}
#qunit-tests td {
vertical-align: top;
}
#qunit-tests pre {
margin: 0;
white-space: pre-wrap;
word-wrap: break-word;
}
#qunit-tests del {
background-color: #e0f2be;
color: #374e0c;
text-decoration: none;
}
#qunit-tests ins {
background-color: #ffcaca;
color: #500;
text-decoration: none;
}
/*** Test Counts */
#qunit-tests b.counts { color: black; }
#qunit-tests b.passed { color: #5E740B; }
#qunit-tests b.failed { color: #710909; }
#qunit-tests li li {
padding: 5px;
background-color: #fff;
border-bottom: none;
list-style-position: inside;
}
/*** Passing Styles */
#qunit-tests li li.pass {
color: #3c510c;
background-color: #fff;
border-left: 10px solid #C6E746;
}
#qunit-tests .pass { color: #528CE0; background-color: #D2E0E6; }
#qunit-tests .pass .test-name { color: #366097; }
#qunit-tests .pass .test-actual,
#qunit-tests .pass .test-expected { color: #999999; }
#qunit-banner.qunit-pass { background-color: #C6E746; }
/*** Failing Styles */
#qunit-tests li li.fail {
color: #710909;
background-color: #fff;
border-left: 10px solid #EE5757;
white-space: pre;
}
#qunit-tests > li:last-child {
border-radius: 0 0 5px 5px;
-moz-border-radius: 0 0 5px 5px;
-webkit-border-bottom-right-radius: 5px;
-webkit-border-bottom-left-radius: 5px;
}
#qunit-tests .fail { color: #000000; background-color: #EE5757; }
#qunit-tests .fail .test-name,
#qunit-tests .fail .module-name { color: #000000; }
#qunit-tests .fail .test-actual { color: #EE5757; }
#qunit-tests .fail .test-expected { color: green; }
#qunit-banner.qunit-fail { background-color: #EE5757; }
/** Result */
#qunit-testresult {
padding: 0.5em 0.5em 0.5em 2.5em;
color: #2b81af;
background-color: #D2E0E6;
border-bottom: 1px solid white;
}
#qunit-testresult .module-name {
font-weight: bold;
}
/** Fixture */
#qunit-fixture {
position: absolute;
top: -10000px;
left: -10000px;
width: 1000px;
height: 1000px;
}

2152
vendor/qunit/qunit/qunit.js vendored Normal file

File diff suppressed because it is too large Load Diff

58
vendor/requirejs/LICENSE vendored Normal file
View File

@@ -0,0 +1,58 @@
RequireJS is released under two licenses: new BSD, and MIT. You may pick the
license that best suits your development needs. The text of both licenses are
provided below.
The "New" BSD License:
----------------------
Copyright (c) 2010-2011, The Dojo Foundation
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the Dojo Foundation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
MIT License
-----------
Copyright (c) 2010-2011, The Dojo Foundation
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.

51
vendor/requirejs/README.md vendored Normal file
View File

@@ -0,0 +1,51 @@
# RequireJS
RequireJS loads plain JavaScript files as well as more defined modules. It is
optimized for in-browser use, including in
[a Web Worker](http://requirejs.org/docs/api.html#webworker), but it can be used
in other JavaScript environments, like Rhino and
[Node](http://requirejs.org/docs/node.html). It implements the
[Asynchronous Module](https://github.com/amdjs/amdjs-api/wiki/AMD)
API.
RequireJS uses plain script tags to load modules/files, so it should allow for
easy debugging. It can be used
[simply to load existing JavaScript files](http://requirejs.org/docs/api.html#jsfiles),
so you can add it to your existing project without having to re-write your
JavaScript files.
RequireJS includes [an optimization tool](http://requirejs.org/docs/optimization.html)
you can run as part of your packaging steps for deploying your code. The
optimization tool can combine and minify your JavaScript files to allow for
better performance.
If the JavaScript file defines a JavaScript module via
[define()](http://requirejs.org/docs/api.html#define), then there are other benefits
RequireJS can offer: [improvements over traditional CommonJS modules](http://requirejs.org/docs/commonjs.html)
and [loading multiple versions](http://requirejs.org/docs/api.html#multiversion)
of a module in a page. RequireJS also has a plugin system that supports features like
[i18n string bundles](http://requirejs.org/docs/api.html#i18n), and
[text file dependencies](http://requirejs.org/docs/api.html#text).
RequireJS does not have any dependencies on a JavaScript framework.
It is dual-licensed -- new BSD or MIT.
The standard require.js file is around 5.5KB when minified via Closure Compiler
and gzipped.
RequireJS works in IE 6+, Firefox 2+, Safari 3.2+, Chrome 3+, and Opera 10+.
[Latest Release](http://requirejs.org/docs/download.html)
## Directories
* **dist**: Scripts and assets to generate the requirejs.org docs, and for
generating a require.js release.
* **docs**: The raw HTML files for the requirejs.org docs. Only includes the
body of each page. Files in **dist** are used to generate a complete HTML page.
* **tests**: Tests for require.js.
* **testBaseUrl.js**: A file used in the tests inside **tests**. Purposely
placed outside the tests directory for testing paths that go outside a baseUrl.
* **updatesubs.sh**: Updates projects that depend on require.js Assumes the
projects are siblings to this directory and have specific names. Useful to
copy require.js to dependent projects easily while in development.

2000
vendor/requirejs/require.js vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,4 @@
Copyright (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative
Reporters & Editors
Copyright (c) 2009-2013 Jeremy Ashkenas, DocumentCloud
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation

19
vendor/underscore/README.md vendored Normal file
View File

@@ -0,0 +1,19 @@
__
/\ \ __
__ __ ___ \_\ \ __ _ __ ____ ___ ___ _ __ __ /\_\ ____
/\ \/\ \ /' _ `\ /'_ \ /'__`\/\ __\/ ,__\ / ___\ / __`\/\ __\/'__`\ \/\ \ /',__\
\ \ \_\ \/\ \/\ \/\ \ \ \/\ __/\ \ \//\__, `\/\ \__//\ \ \ \ \ \//\ __/ __ \ \ \/\__, `\
\ \____/\ \_\ \_\ \___,_\ \____\\ \_\\/\____/\ \____\ \____/\ \_\\ \____\/\_\ _\ \ \/\____/
\/___/ \/_/\/_/\/__,_ /\/____/ \/_/ \/___/ \/____/\/___/ \/_/ \/____/\/_//\ \_\ \/___/
\ \____/
\/___/
Underscore.js is a utility-belt library for JavaScript that provides
support for the usual functional suspects (each, map, reduce, filter...)
without extending any core JavaScript objects.
For Docs, License, Tests, and pre-packed downloads, see:
http://underscorejs.org
Many thanks to our contributors:
https://github.com/documentcloud/underscore/contributors

View File

@@ -1,310 +1,158 @@
(function() {
var _ = typeof require == 'function' ? require('..') : window._;
$(document).ready(function() {
QUnit.module('Arrays');
module("Arrays");
test('first', function() {
equal(_.first([1, 2, 3]), 1, 'can pull out the first element of an array');
test("first", function() {
equal(_.first([1,2,3]), 1, 'can pull out the first element of an array');
equal(_([1, 2, 3]).first(), 1, 'can perform OO-style "first()"');
deepEqual(_.first([1, 2, 3], 0), [], 'can pass an index to first');
deepEqual(_.first([1, 2, 3], 2), [1, 2], 'can pass an index to first');
deepEqual(_.first([1, 2, 3], 5), [1, 2, 3], 'can pass an index to first');
var result = (function(){ return _.first(arguments); }(4, 3, 2, 1));
equal(_.first([1,2,3], 0).join(', '), "", 'can pass an index to first');
equal(_.first([1,2,3], 2).join(', '), '1, 2', 'can pass an index to first');
equal(_.first([1,2,3], 5).join(', '), '1, 2, 3', 'can pass an index to first');
var result = (function(){ return _.first(arguments); })(4, 3, 2, 1);
equal(result, 4, 'works on an arguments object.');
result = _.map([[1, 2, 3], [1, 2, 3]], _.first);
deepEqual(result, [1, 1], 'works well with _.map');
result = (function() { return _.first([1, 2, 3], 2); }());
deepEqual(result, [1, 2]);
result = _.map([[1,2,3],[1,2,3]], _.first);
equal(result.join(','), '1,1', 'works well with _.map');
result = (function() { return _.take([1,2,3], 2); })();
equal(result.join(','), '1,2', 'aliased as take');
equal(_.first(null), undefined, 'handles nulls');
strictEqual(_.first([1, 2, 3], -1).length, 0);
});
test('head', function() {
strictEqual(_.first, _.head, 'alias for first');
});
test('take', function() {
strictEqual(_.first, _.take, 'alias for first');
});
test('rest', function() {
test("rest", function() {
var numbers = [1, 2, 3, 4];
deepEqual(_.rest(numbers), [2, 3, 4], 'working rest()');
deepEqual(_.rest(numbers, 0), [1, 2, 3, 4], 'working rest(0)');
deepEqual(_.rest(numbers, 2), [3, 4], 'rest can take an index');
var result = (function(){ return _(arguments).rest(); }(1, 2, 3, 4));
deepEqual(result, [2, 3, 4], 'works on arguments object');
result = _.map([[1, 2, 3], [1, 2, 3]], _.rest);
deepEqual(_.flatten(result), [2, 3, 2, 3], 'works well with _.map');
result = (function(){ return _(arguments).rest(); }(1, 2, 3, 4));
deepEqual(result, [2, 3, 4], 'works on arguments object');
equal(_.rest(numbers).join(", "), "2, 3, 4", 'working rest()');
equal(_.rest(numbers, 0).join(", "), "1, 2, 3, 4", 'working rest(0)');
equal(_.rest(numbers, 2).join(', '), '3, 4', 'rest can take an index');
var result = (function(){ return _(arguments).tail(); })(1, 2, 3, 4);
equal(result.join(', '), '2, 3, 4', 'aliased as tail and works on arguments object');
result = _.map([[1,2,3],[1,2,3]], _.rest);
equal(_.flatten(result).join(','), '2,3,2,3', 'works well with _.map');
result = (function(){ return _(arguments).drop(); })(1, 2, 3, 4);
equal(result.join(', '), '2, 3, 4', 'aliased as drop and works on arguments object');
});
test('tail', function() {
strictEqual(_.rest, _.tail, 'alias for rest');
test("initial", function() {
equal(_.initial([1,2,3,4,5]).join(", "), "1, 2, 3, 4", 'working initial()');
equal(_.initial([1,2,3,4],2).join(", "), "1, 2", 'initial can take an index');
var result = (function(){ return _(arguments).initial(); })(1, 2, 3, 4);
equal(result.join(", "), "1, 2, 3", 'initial works on arguments object');
result = _.map([[1,2,3],[1,2,3]], _.initial);
equal(_.flatten(result).join(','), '1,2,1,2', 'initial works with _.map');
});
test('drop', function() {
strictEqual(_.rest, _.drop, 'alias for rest');
});
test('initial', function() {
deepEqual(_.initial([1, 2, 3, 4, 5]), [1, 2, 3, 4], 'working initial()');
deepEqual(_.initial([1, 2, 3, 4], 2), [1, 2], 'initial can take an index');
deepEqual(_.initial([1, 2, 3, 4], 6), [], 'initial can take a large index');
var result = (function(){ return _(arguments).initial(); }(1, 2, 3, 4));
deepEqual(result, [1, 2, 3], 'initial works on arguments object');
result = _.map([[1, 2, 3], [1, 2, 3]], _.initial);
deepEqual(_.flatten(result), [1, 2, 1, 2], 'initial works with _.map');
});
test('last', function() {
equal(_.last([1, 2, 3]), 3, 'can pull out the last element of an array');
deepEqual(_.last([1, 2, 3], 0), [], 'can pass an index to last');
deepEqual(_.last([1, 2, 3], 2), [2, 3], 'can pass an index to last');
deepEqual(_.last([1, 2, 3], 5), [1, 2, 3], 'can pass an index to last');
var result = (function(){ return _(arguments).last(); }(1, 2, 3, 4));
test("last", function() {
equal(_.last([1,2,3]), 3, 'can pull out the last element of an array');
equal(_.last([1,2,3], 0).join(', '), "", 'can pass an index to last');
equal(_.last([1,2,3], 2).join(', '), '2, 3', 'can pass an index to last');
equal(_.last([1,2,3], 5).join(', '), '1, 2, 3', 'can pass an index to last');
var result = (function(){ return _(arguments).last(); })(1, 2, 3, 4);
equal(result, 4, 'works on an arguments object');
result = _.map([[1, 2, 3], [1, 2, 3]], _.last);
deepEqual(result, [3, 3], 'works well with _.map');
result = _.map([[1,2,3],[1,2,3]], _.last);
equal(result.join(','), '3,3', 'works well with _.map');
equal(_.last(null), undefined, 'handles nulls');
strictEqual(_.last([1, 2, 3], -1).length, 0);
});
test('compact', function() {
test("compact", function() {
equal(_.compact([0, 1, false, 2, false, 3]).length, 3, 'can trim out all falsy values');
var result = (function(){ return _.compact(arguments).length; }(0, 1, false, 2, false, 3));
var result = (function(){ return _.compact(arguments).length; })(0, 1, false, 2, false, 3);
equal(result, 3, 'works on an arguments object');
});
test('flatten', function() {
deepEqual(_.flatten(null), [], 'Flattens supports null');
deepEqual(_.flatten(void 0), [], 'Flattens supports undefined');
deepEqual(_.flatten([[], [[]], []]), [], 'Flattens empty arrays');
deepEqual(_.flatten([[], [[]], []], true), [[]], 'Flattens empty arrays');
test("flatten", function() {
var list = [1, [2], [3, [[[4]]]]];
deepEqual(_.flatten(list), [1, 2, 3, 4], 'can flatten nested arrays');
deepEqual(_.flatten(list, true), [1, 2, 3, [[[4]]]], 'can shallowly flatten nested arrays');
var result = (function(){ return _.flatten(arguments); }(1, [2], [3, [[[4]]]]));
deepEqual(result, [1, 2, 3, 4], 'works on an arguments object');
list = [[1], [2], [3], [[4]]];
deepEqual(_.flatten(list, true), [1, 2, 3, [4]], 'can shallowly flatten arrays containing only other arrays');
equal(_.flatten([_.range(10), _.range(10), 5, 1, 3], true).length, 23);
equal(_.flatten([_.range(10), _.range(10), 5, 1, 3]).length, 23);
equal(_.flatten([new Array(1000000), _.range(56000), 5, 1, 3]).length, 1056003, 'Flatten can handle massive collections');
equal(_.flatten([new Array(1000000), _.range(56000), 5, 1, 3], true).length, 1056003, 'Flatten can handle massive collections');
deepEqual(_.flatten(list), [1,2,3,4], 'can flatten nested arrays');
deepEqual(_.flatten(list, true), [1,2,3,[[[4]]]], 'can shallowly flatten nested arrays');
var result = (function(){ return _.flatten(arguments); })(1, [2], [3, [[[4]]]]);
deepEqual(result, [1,2,3,4], 'works on an arguments object');
});
test('without', function() {
test("without", function() {
var list = [1, 2, 1, 0, 3, 1, 4];
deepEqual(_.without(list, 0, 1), [2, 3, 4], 'can remove all instances of an object');
var result = (function(){ return _.without(arguments, 0, 1); }(1, 2, 1, 0, 3, 1, 4));
deepEqual(result, [2, 3, 4], 'works on an arguments object');
equal(_.without(list, 0, 1).join(', '), '2, 3, 4', 'can remove all instances of an object');
var result = (function(){ return _.without(arguments, 0, 1); })(1, 2, 1, 0, 3, 1, 4);
equal(result.join(', '), '2, 3, 4', 'works on an arguments object');
list = [{one : 1}, {two : 2}];
equal(_.without(list, {one : 1}).length, 2, 'uses real object identity for comparisons.');
equal(_.without(list, list[0]).length, 1, 'ditto.');
var list = [{one : 1}, {two : 2}];
ok(_.without(list, {one : 1}).length == 2, 'uses real object identity for comparisons.');
ok(_.without(list, list[0]).length == 1, 'ditto.');
});
test('sortedIndex', function() {
var numbers = [10, 20, 30, 40, 50], num = 35;
var indexForNum = _.sortedIndex(numbers, num);
equal(indexForNum, 3, '35 should be inserted at index 3');
var indexFor30 = _.sortedIndex(numbers, 30);
equal(indexFor30, 2, '30 should be inserted at index 2');
var objects = [{x: 10}, {x: 20}, {x: 30}, {x: 40}];
var iterator = function(obj){ return obj.x; };
strictEqual(_.sortedIndex(objects, {x: 25}, iterator), 2);
strictEqual(_.sortedIndex(objects, {x: 35}, 'x'), 3);
var context = {1: 2, 2: 3, 3: 4};
iterator = function(obj){ return this[obj]; };
strictEqual(_.sortedIndex([1, 3], 2, iterator, context), 1);
var values = [0, 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535, 131071, 262143, 524287, 1048575, 2097151, 4194303, 8388607, 16777215, 33554431, 67108863, 134217727, 268435455, 536870911, 1073741823, 2147483647];
var array = Array(Math.pow(2, 32) - 1);
var length = values.length;
while (length--) {
array[values[length]] = values[length];
}
equal(_.sortedIndex(array, 2147483648), 2147483648, 'should work with large indexes');
});
test('uniq', function() {
test("uniq", function() {
var list = [1, 2, 1, 3, 1, 4];
deepEqual(_.uniq(list), [1, 2, 3, 4], 'can find the unique values of an unsorted array');
equal(_.uniq(list).join(', '), '1, 2, 3, 4', 'can find the unique values of an unsorted array');
list = [1, 1, 1, 2, 2, 3];
deepEqual(_.uniq(list, true), [1, 2, 3], 'can find the unique values of a sorted array faster');
var list = [1, 1, 1, 2, 2, 3];
equal(_.uniq(list, true).join(', '), '1, 2, 3', 'can find the unique values of a sorted array faster');
list = [{name: 'moe'}, {name: 'curly'}, {name: 'larry'}, {name: 'curly'}];
var list = [{name:'moe'}, {name:'curly'}, {name:'larry'}, {name:'curly'}];
var iterator = function(value) { return value.name; };
deepEqual(_.map(_.uniq(list, false, iterator), iterator), ['moe', 'curly', 'larry'], 'can find the unique values of an array using a custom iterator');
equal(_.map(_.uniq(list, false, iterator), iterator).join(', '), 'moe, curly, larry', 'can find the unique values of an array using a custom iterator');
deepEqual(_.map(_.uniq(list, iterator), iterator), ['moe', 'curly', 'larry'], 'can find the unique values of an array using a custom iterator without specifying whether array is sorted');
equal(_.map(_.uniq(list, iterator), iterator).join(', '), 'moe, curly, larry', 'can find the unique values of an array using a custom iterator without specifying whether array is sorted');
iterator = function(value) { return value + 1; };
list = [1, 2, 2, 3, 4, 4];
deepEqual(_.uniq(list, true, iterator), [1, 2, 3, 4], 'iterator works with sorted array');
var iterator = function(value) { return value +1; };
var list = [1, 2, 2, 3, 4, 4];
equal(_.uniq(list, true, iterator).join(', '), '1, 2, 3, 4', 'iterator works with sorted array');
var kittens = [
{kitten: 'Celery', cuteness: 8},
{kitten: 'Juniper', cuteness: 10},
{kitten: 'Spottis', cuteness: 10}
];
var expected = [
{kitten: 'Celery', cuteness: 8},
{kitten: 'Juniper', cuteness: 10}
];
deepEqual(_.uniq(kittens, true, 'cuteness'), expected, 'string iterator works with sorted array');
var result = (function(){ return _.uniq(arguments); }(1, 2, 1, 3, 1, 4));
deepEqual(result, [1, 2, 3, 4], 'works on an arguments object');
var a = {}, b = {}, c = {};
deepEqual(_.uniq([a, b, a, b, c]), [a, b, c], 'works on values that can be tested for equivalency but not ordered');
deepEqual(_.uniq(null), []);
var context = {};
list = [3];
_.uniq(list, function(value, index, array) {
strictEqual(this, context);
strictEqual(value, 3);
strictEqual(index, 0);
strictEqual(array, list);
}, context);
deepEqual(_.uniq([{a: 1, b: 1}, {a: 1, b: 2}, {a: 1, b: 3}, {a: 2, b: 1}], 'a'), [{a: 1, b: 1}, {a: 2, b: 1}], 'can use pluck like iterator');
deepEqual(_.uniq([{0: 1, b: 1}, {0: 1, b: 2}, {0: 1, b: 3}, {0: 2, b: 1}], 0), [{0: 1, b: 1}, {0: 2, b: 1}], 'can use falsey pluck like iterator');
var result = (function(){ return _.uniq(arguments); })(1, 2, 1, 3, 1, 4);
equal(result.join(', '), '1, 2, 3, 4', 'works on an arguments object');
});
test('unique', function() {
strictEqual(_.uniq, _.unique, 'alias for uniq');
});
test('intersection', function() {
test("intersection", function() {
var stooges = ['moe', 'curly', 'larry'], leaders = ['moe', 'groucho'];
deepEqual(_.intersection(stooges, leaders), ['moe'], 'can take the set intersection of two arrays');
deepEqual(_(stooges).intersection(leaders), ['moe'], 'can perform an OO-style intersection');
var result = (function(){ return _.intersection(arguments, leaders); }('moe', 'curly', 'larry'));
deepEqual(result, ['moe'], 'works on an arguments object');
var theSixStooges = ['moe', 'moe', 'curly', 'curly', 'larry', 'larry'];
deepEqual(_.intersection(theSixStooges, leaders), ['moe'], 'returns a duplicate-free array');
result = _.intersection([2, 4, 3, 1], [1, 2, 3]);
deepEqual(result, [2, 3, 1], 'preserves order of first array');
result = _.intersection(null, [1, 2, 3]);
equal(Object.prototype.toString.call(result), '[object Array]', 'returns an empty array when passed null as first argument');
equal(result.length, 0, 'returns an empty array when passed null as first argument');
result = _.intersection([1, 2, 3], null);
equal(Object.prototype.toString.call(result), '[object Array]', 'returns an empty array when passed null as argument beyond the first');
equal(result.length, 0, 'returns an empty array when passed null as argument beyond the first');
equal(_.intersection(stooges, leaders).join(''), 'moe', 'can take the set intersection of two arrays');
equal(_(stooges).intersection(leaders).join(''), 'moe', 'can perform an OO-style intersection');
var result = (function(){ return _.intersection(arguments, leaders); })('moe', 'curly', 'larry');
equal(result.join(''), 'moe', 'works on an arguments object');
});
test('union', function() {
test("union", function() {
var result = _.union([1, 2, 3], [2, 30, 1], [1, 40]);
deepEqual(result, [1, 2, 3, 30, 40], 'takes the union of a list of arrays');
equal(result.join(' '), '1 2 3 30 40', 'takes the union of a list of arrays');
result = _.union([1, 2, 3], [2, 30, 1], [1, 40, [1]]);
deepEqual(result, [1, 2, 3, 30, 40, [1]], 'takes the union of a list of nested arrays');
var args = null;
(function(){ args = arguments; }(1, 2, 3));
result = _.union(args, [2, 30, 1], [1, 40]);
deepEqual(result, [1, 2, 3, 30, 40], 'takes the union of a list of arrays');
result = _.union([1, 2, 3], 4);
deepEqual(result, [1, 2, 3], 'restrict the union to arrays only');
var result = _.union([1, 2, 3], [2, 30, 1], [1, 40, [1]]);
equal(result.join(' '), '1 2 3 30 40 1', 'takes the union of a list of nested arrays');
});
test('difference', function() {
test("difference", function() {
var result = _.difference([1, 2, 3], [2, 30, 40]);
deepEqual(result, [1, 3], 'takes the difference of two arrays');
equal(result.join(' '), '1 3', 'takes the difference of two arrays');
result = _.difference([1, 2, 3, 4], [2, 30, 40], [1, 11, 111]);
deepEqual(result, [3, 4], 'takes the difference of three arrays');
result = _.difference([1, 2, 3], 1);
deepEqual(result, [1, 2, 3], 'restrict the difference to arrays only');
var result = _.difference([1, 2, 3, 4], [2, 30, 40], [1, 11, 111]);
equal(result.join(' '), '3 4', 'takes the difference of three arrays');
});
test('zip', function() {
var names = ['moe', 'larry', 'curly'], ages = [30, 40, 50], leaders = [true];
deepEqual(_.zip(names, ages, leaders), [
['moe', 30, true],
['larry', 40, undefined],
['curly', 50, undefined]
], 'zipped together arrays of different lengths');
var stooges = _.zip(['moe', 30, 'stooge 1'], ['larry', 40, 'stooge 2'], ['curly', 50, 'stooge 3']);
deepEqual(stooges, [['moe', 'larry', 'curly'], [30, 40, 50], ['stooge 1', 'stooge 2', 'stooge 3']], 'zipped pairs');
// In the case of difference lengths of the tuples undefineds
// should be used as placeholder
stooges = _.zip(['moe', 30], ['larry', 40], ['curly', 50, 'extra data']);
deepEqual(stooges, [['moe', 'larry', 'curly'], [30, 40, 50], [undefined, undefined, 'extra data']], 'zipped pairs with empties');
var empty = _.zip([]);
deepEqual(empty, [], 'unzipped empty');
deepEqual(_.zip(null), [], 'handles null');
deepEqual(_.zip(), [], '_.zip() returns []');
});
test('unzip', function() {
deepEqual(_.unzip(null), [], 'handles null');
deepEqual(_.unzip([['a', 'b'], [1, 2]]), [['a', 1], ['b', 2]]);
// complements zip
var zipped = _.zip(['fred', 'barney'], [30, 40], [true, false]);
deepEqual(_.unzip(zipped), [['fred', 'barney'], [30, 40], [true, false]]);
zipped = _.zip(['moe', 30], ['larry', 40], ['curly', 50, 'extra data']);
deepEqual(_.unzip(zipped), [['moe', 30, void 0], ['larry', 40, void 0], ['curly', 50, 'extra data']], 'Uses length of largest array');
var stooges = _.zip(names, ages, leaders);
equal(String(stooges), 'moe,30,true,larry,40,,curly,50,', 'zipped together arrays of different lengths');
});
test('object', function() {
var result = _.object(['moe', 'larry', 'curly'], [30, 40, 50]);
var shouldBe = {moe: 30, larry: 40, curly: 50};
deepEqual(result, shouldBe, 'two arrays zipped together into an object');
ok(_.isEqual(result, shouldBe), 'two arrays zipped together into an object');
result = _.object([['one', 1], ['two', 2], ['three', 3]]);
shouldBe = {one: 1, two: 2, three: 3};
deepEqual(result, shouldBe, 'an array of pairs zipped together into an object');
ok(_.isEqual(result, shouldBe), 'an array of pairs zipped together into an object');
var stooges = {moe: 30, larry: 40, curly: 50};
deepEqual(_.object(_.pairs(stooges)), stooges, 'an object converted to pairs and back to an object');
ok(_.isEqual(_.object(_.pairs(stooges)), stooges), 'an object converted to pairs and back to an object');
deepEqual(_.object(null), {}, 'handles nulls');
ok(_.isEqual(_.object(null), {}), 'handles nulls');
});
test('indexOf', function() {
test("indexOf", function() {
var numbers = [1, 2, 3];
equal(_.indexOf(numbers, 2), 1, 'can compute indexOf');
var result = (function(){ return _.indexOf(arguments, 2); }(1, 2, 3));
numbers.indexOf = null;
equal(_.indexOf(numbers, 2), 1, 'can compute indexOf, even without the native function');
var result = (function(){ return _.indexOf(arguments, 2); })(1, 2, 3);
equal(result, 1, 'works on an arguments object');
equal(_.indexOf(null, 2), -1, 'handles nulls properly');
_.each([null, void 0, [], false], function(val) {
var msg = 'Handles: ' + (_.isArray(val) ? '[]' : val);
equal(_.indexOf(val, 2), -1, msg);
equal(_.indexOf(val, 2, -1), -1, msg);
equal(_.indexOf(val, 2, -20), -1, msg);
equal(_.indexOf(val, 2, 15), -1, msg);
});
var num = 35;
numbers = [10, 20, 30, 40, 50];
var numbers = [10, 20, 30, 40, 50], num = 35;
var index = _.indexOf(numbers, num, true);
equal(index, -1, '35 is not in the list');
@@ -313,225 +161,40 @@
equal(index, 3, '40 is in the list');
numbers = [1, 40, 40, 40, 40, 40, 40, 40, 50, 60, 70]; num = 40;
equal(_.indexOf(numbers, num, true), 1, '40 is in the list');
equal(_.indexOf(numbers, 6, true), -1, '6 isnt in the list');
equal(_.indexOf([1, 2, 5, 4, 6, 7], 5, true), -1, 'sorted indexOf doesn\'t uses binary search');
ok(_.every(['1', [], {}, null], function() {
return _.indexOf(numbers, num, {}) === 1;
}), 'non-nums as fromIndex make indexOf assume sorted');
index = _.indexOf(numbers, num, true);
equal(index, 1, '40 is in the list');
numbers = [1, 2, 3, 1, 2, 3, 1, 2, 3];
index = _.indexOf(numbers, 2, 5);
equal(index, 7, 'supports the fromIndex argument');
index = _.indexOf([,,,], undefined);
equal(index, 0, 'treats sparse arrays as if they were dense');
var array = [1, 2, 3, 1, 2, 3];
strictEqual(_.indexOf(array, 1, -3), 3, 'neg `fromIndex` starts at the right index');
strictEqual(_.indexOf(array, 1, -2), -1, 'neg `fromIndex` starts at the right index');
strictEqual(_.indexOf(array, 2, -3), 4);
_.each([-6, -8, -Infinity], function(fromIndex) {
strictEqual(_.indexOf(array, 1, fromIndex), 0);
});
strictEqual(_.indexOf([1, 2, 3], 1, true), 0);
index = _.indexOf([], undefined, true);
equal(index, -1, 'empty array with truthy `isSorted` returns -1');
});
test('indexOf with NaN', function() {
strictEqual(_.indexOf([1, 2, NaN, NaN], NaN), 2, 'Expected [1, 2, NaN] to contain NaN');
strictEqual(_.indexOf([1, 2, Infinity], NaN), -1, 'Expected [1, 2, NaN] to contain NaN');
strictEqual(_.indexOf([1, 2, NaN, NaN], NaN, 1), 2, 'startIndex does not affect result');
strictEqual(_.indexOf([1, 2, NaN, NaN], NaN, -2), 2, 'startIndex does not affect result');
(function() {
strictEqual(_.indexOf(arguments, NaN), 2, 'Expected arguments [1, 2, NaN] to contain NaN');
}(1, 2, NaN, NaN));
});
test('indexOf with +- 0', function() {
_.each([-0, +0], function(val) {
strictEqual(_.indexOf([1, 2, val, val], val), 2);
strictEqual(_.indexOf([1, 2, val, val], -val), 2);
});
});
test('lastIndexOf', function() {
test("lastIndexOf", function() {
var numbers = [1, 0, 1];
var falsey = [void 0, '', 0, false, NaN, null, undefined];
equal(_.lastIndexOf(numbers, 1), 2);
numbers = [1, 0, 1, 0, 0, 1, 0, 0, 0];
numbers.lastIndexOf = null;
equal(_.lastIndexOf(numbers, 1), 5, 'can compute lastIndexOf, even without the native function');
equal(_.lastIndexOf(numbers, 0), 8, 'lastIndexOf the other element');
var result = (function(){ return _.lastIndexOf(arguments, 1); }(1, 0, 1, 0, 0, 1, 0, 0, 0));
var result = (function(){ return _.lastIndexOf(arguments, 1); })(1, 0, 1, 0, 0, 1, 0, 0, 0);
equal(result, 5, 'works on an arguments object');
_.each([null, void 0, [], false], function(val) {
var msg = 'Handles: ' + (_.isArray(val) ? '[]' : val);
equal(_.lastIndexOf(val, 2), -1, msg);
equal(_.lastIndexOf(val, 2, -1), -1, msg);
equal(_.lastIndexOf(val, 2, -20), -1, msg);
equal(_.lastIndexOf(val, 2, 15), -1, msg);
});
equal(_.indexOf(null, 2), -1, 'handles nulls properly');
numbers = [1, 2, 3, 1, 2, 3, 1, 2, 3];
var index = _.lastIndexOf(numbers, 2, 2);
equal(index, 1, 'supports the fromIndex argument');
var array = [1, 2, 3, 1, 2, 3];
strictEqual(_.lastIndexOf(array, 1, 0), 0, 'starts at the correct from idx');
strictEqual(_.lastIndexOf(array, 3), 5, 'should return the index of the last matched value');
strictEqual(_.lastIndexOf(array, 4), -1, 'should return `-1` for an unmatched value');
strictEqual(_.lastIndexOf(array, 1, 2), 0, 'should work with a positive `fromIndex`');
_.each([6, 8, Math.pow(2, 32), Infinity], function(fromIndex) {
strictEqual(_.lastIndexOf(array, undefined, fromIndex), -1);
strictEqual(_.lastIndexOf(array, 1, fromIndex), 3);
strictEqual(_.lastIndexOf(array, '', fromIndex), -1);
});
var expected = _.map(falsey, function(value) {
return typeof value == 'number' ? -1 : 5;
});
var actual = _.map(falsey, function(fromIndex) {
return _.lastIndexOf(array, 3, fromIndex);
});
deepEqual(actual, expected, 'should treat falsey `fromIndex` values, except `0` and `NaN`, as `array.length`');
strictEqual(_.lastIndexOf(array, 3, '1'), 5, 'should treat non-number `fromIndex` values as `array.length`');
strictEqual(_.lastIndexOf(array, 3, true), 5, 'should treat non-number `fromIndex` values as `array.length`');
strictEqual(_.lastIndexOf(array, 2, -3), 1, 'should work with a negative `fromIndex`');
strictEqual(_.lastIndexOf(array, 1, -3), 3, 'neg `fromIndex` starts at the right index');
deepEqual(_.map([-6, -8, -Infinity], function(fromIndex) {
return _.lastIndexOf(array, 1, fromIndex);
}), [0, -1, -1]);
});
test('lastIndexOf with NaN', function() {
strictEqual(_.lastIndexOf([1, 2, NaN, NaN], NaN), 3, 'Expected [1, 2, NaN] to contain NaN');
strictEqual(_.lastIndexOf([1, 2, Infinity], NaN), -1, 'Expected [1, 2, NaN] to contain NaN');
strictEqual(_.lastIndexOf([1, 2, NaN, NaN], NaN, 2), 2, 'fromIndex does not affect result');
strictEqual(_.lastIndexOf([1, 2, NaN, NaN], NaN, -2), 2, 'fromIndex does not affect result');
(function() {
strictEqual(_.lastIndexOf(arguments, NaN), 3, 'Expected arguments [1, 2, NaN] to contain NaN');
}(1, 2, NaN, NaN));
test("range", function() {
equal(_.range(0).join(''), '', 'range with 0 as a first argument generates an empty array');
equal(_.range(4).join(' '), '0 1 2 3', 'range with a single positive argument generates an array of elements 0,1,2,...,n-1');
equal(_.range(5, 8).join(' '), '5 6 7', 'range with two arguments a &amp; b, a&lt;b generates an array of elements a,a+1,a+2,...,b-2,b-1');
equal(_.range(8, 5).join(''), '', 'range with two arguments a &amp; b, b&lt;a generates an empty array');
equal(_.range(3, 10, 3).join(' '), '3 6 9', 'range with three arguments a &amp; b &amp; c, c &lt; b-a, a &lt; b generates an array of elements a,a+c,a+2c,...,b - (multiplier of a) &lt; c');
equal(_.range(3, 10, 15).join(''), '3', 'range with three arguments a &amp; b &amp; c, c &gt; b-a, a &lt; b generates an array with a single element, equal to a');
equal(_.range(12, 7, -2).join(' '), '12 10 8', 'range with three arguments a &amp; b &amp; c, a &gt; b, c &lt; 0 generates an array of elements a,a-c,a-2c and ends with the number not less than b');
equal(_.range(0, -10, -1).join(' '), '0 -1 -2 -3 -4 -5 -6 -7 -8 -9', 'final example in the Python docs');
});
test('lastIndexOf with +- 0', function() {
_.each([-0, +0], function(val) {
strictEqual(_.lastIndexOf([1, 2, val, val], val), 3);
strictEqual(_.lastIndexOf([1, 2, val, val], -val), 3);
strictEqual(_.lastIndexOf([-1, 1, 2], -val), -1);
});
});
test('findIndex', function() {
var objects = [
{'a': 0, 'b': 0},
{'a': 1, 'b': 1},
{'a': 2, 'b': 2},
{'a': 0, 'b': 0}
];
equal(_.findIndex(objects, function(obj) {
return obj.a === 0;
}), 0);
equal(_.findIndex(objects, function(obj) {
return obj.b * obj.a === 4;
}), 2);
equal(_.findIndex(objects, 'a'), 1, 'Uses lookupIterator');
equal(_.findIndex(objects, function(obj) {
return obj.b * obj.a === 5;
}), -1);
equal(_.findIndex(null, _.noop), -1);
strictEqual(_.findIndex(objects, function(a) {
return a.foo === null;
}), -1);
_.findIndex([{a: 1}], function(a, key, obj) {
equal(key, 0);
deepEqual(obj, [{a: 1}]);
strictEqual(this, objects, 'called with context');
}, objects);
var sparse = [];
sparse[20] = {'a': 2, 'b': 2};
equal(_.findIndex(sparse, function(obj) {
return obj && obj.b * obj.a === 4;
}), 20, 'Works with sparse arrays');
var array = [1, 2, 3, 4];
array.match = 55;
strictEqual(_.findIndex(array, function(x) { return x === 55; }), -1, 'doesn\'t match array-likes keys');
});
test('findLastIndex', function() {
var objects = [
{'a': 0, 'b': 0},
{'a': 1, 'b': 1},
{'a': 2, 'b': 2},
{'a': 0, 'b': 0}
];
equal(_.findLastIndex(objects, function(obj) {
return obj.a === 0;
}), 3);
equal(_.findLastIndex(objects, function(obj) {
return obj.b * obj.a === 4;
}), 2);
equal(_.findLastIndex(objects, 'a'), 2, 'Uses lookupIterator');
equal(_.findLastIndex(objects, function(obj) {
return obj.b * obj.a === 5;
}), -1);
equal(_.findLastIndex(null, _.noop), -1);
strictEqual(_.findLastIndex(objects, function(a) {
return a.foo === null;
}), -1);
_.findLastIndex([{a: 1}], function(a, key, obj) {
equal(key, 0);
deepEqual(obj, [{a: 1}]);
strictEqual(this, objects, 'called with context');
}, objects);
var sparse = [];
sparse[20] = {'a': 2, 'b': 2};
equal(_.findLastIndex(sparse, function(obj) {
return obj && obj.b * obj.a === 4;
}), 20, 'Works with sparse arrays');
var array = [1, 2, 3, 4];
array.match = 55;
strictEqual(_.findLastIndex(array, function(x) { return x === 55; }), -1, 'doesn\'t match array-likes keys');
});
test('range', function() {
deepEqual(_.range(0), [], 'range with 0 as a first argument generates an empty array');
deepEqual(_.range(4), [0, 1, 2, 3], 'range with a single positive argument generates an array of elements 0,1,2,...,n-1');
deepEqual(_.range(5, 8), [5, 6, 7], 'range with two arguments a &amp; b, a&lt;b generates an array of elements a,a+1,a+2,...,b-2,b-1');
deepEqual(_.range(8, 5), [], 'range with two arguments a &amp; b, b&lt;a generates an empty array');
deepEqual(_.range(3, 10, 3), [3, 6, 9], 'range with three arguments a &amp; b &amp; c, c &lt; b-a, a &lt; b generates an array of elements a,a+c,a+2c,...,b - (multiplier of a) &lt; c');
deepEqual(_.range(3, 10, 15), [3], 'range with three arguments a &amp; b &amp; c, c &gt; b-a, a &lt; b generates an array with a single element, equal to a');
deepEqual(_.range(12, 7, -2), [12, 10, 8], 'range with three arguments a &amp; b &amp; c, a &gt; b, c &lt; 0 generates an array of elements a,a-c,a-2c and ends with the number not less than b');
deepEqual(_.range(0, -10, -1), [0, -1, -2, -3, -4, -5, -6, -7, -8, -9], 'final example in the Python docs');
});
}());
});

View File

@@ -1,14 +1,13 @@
(function() {
var _ = typeof require == 'function' ? require('..') : window._;
$(document).ready(function() {
QUnit.module('Chaining');
module("Chaining");
test('map/flatten/reduce', function() {
test("map/flatten/reduce", function() {
var lyrics = [
'I\'m a lumberjack and I\'m okay',
'I sleep all night and I work all day',
'He\'s a lumberjack and he\'s okay',
'He sleeps all night and he works all day'
"I'm a lumberjack and I'm okay",
"I sleep all night and I work all day",
"He's a lumberjack and he's okay",
"He sleeps all night and he works all day"
];
var counts = _(lyrics).chain()
.map(function(line) { return line.split(''); })
@@ -18,36 +17,35 @@
hash[l]++;
return hash;
}, {}).value();
equal(counts.a, 16, 'counted all the letters in the song');
equal(counts.e, 10, 'counted all the letters in the song');
ok(counts['a'] == 16 && counts['e'] == 10, 'counted all the letters in the song');
});
test('select/reject/sortBy', function() {
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
test("select/reject/sortBy", function() {
var numbers = [1,2,3,4,5,6,7,8,9,10];
numbers = _(numbers).chain().select(function(n) {
return n % 2 === 0;
return n % 2 == 0;
}).reject(function(n) {
return n % 4 === 0;
return n % 4 == 0;
}).sortBy(function(n) {
return -n;
}).value();
deepEqual(numbers, [10, 6, 2], 'filtered and reversed the numbers');
equal(numbers.join(', '), "10, 6, 2", "filtered and reversed the numbers");
});
test('select/reject/sortBy in functional style', function() {
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
test("select/reject/sortBy in functional style", function() {
var numbers = [1,2,3,4,5,6,7,8,9,10];
numbers = _.chain(numbers).select(function(n) {
return n % 2 === 0;
return n % 2 == 0;
}).reject(function(n) {
return n % 4 === 0;
return n % 4 == 0;
}).sortBy(function(n) {
return -n;
}).value();
deepEqual(numbers, [10, 6, 2], 'filtered and reversed the numbers');
equal(numbers.join(', '), "10, 6, 2", "filtered and reversed the numbers");
});
test('reverse/concat/unshift/pop/map', function() {
var numbers = [1, 2, 3, 4, 5];
test("reverse/concat/unshift/pop/map", function() {
var numbers = [1,2,3,4,5];
numbers = _(numbers).chain()
.reverse()
.concat([5, 5, 5])
@@ -55,44 +53,7 @@
.pop()
.map(function(n){ return n * 2; })
.value();
deepEqual(numbers, [34, 10, 8, 6, 4, 2, 10, 10], 'can chain together array functions.');
equal(numbers.join(', '), "34, 10, 8, 6, 4, 2, 10, 10", 'can chain together array functions.');
});
test('splice', function() {
var instance = _([1, 2, 3, 4, 5]).chain();
deepEqual(instance.splice(1, 3).value(), [1, 5]);
deepEqual(instance.splice(1, 0).value(), [1, 5]);
deepEqual(instance.splice(1, 1).value(), [1]);
deepEqual(instance.splice(0, 1).value(), [], '#397 Can create empty array');
});
test('shift', function() {
var instance = _([1, 2, 3]).chain();
deepEqual(instance.shift().value(), [2, 3]);
deepEqual(instance.shift().value(), [3]);
deepEqual(instance.shift().value(), [], '#397 Can create empty array');
});
test('pop', function() {
var instance = _([1, 2, 3]).chain();
deepEqual(instance.pop().value(), [1, 2]);
deepEqual(instance.pop().value(), [1]);
deepEqual(instance.pop().value(), [], '#397 Can create empty array');
});
test('chaining works in small stages', function() {
var o = _([1, 2, 3, 4]).chain();
deepEqual(o.filter(function(i) { return i < 3; }).value(), [1, 2]);
deepEqual(o.filter(function(i) { return i > 2; }).value(), [3, 4]);
});
test('#1562: Engine proxies for chained functions', function() {
var wrapped = _(512);
strictEqual(wrapped.toJSON(), 512);
strictEqual(wrapped.valueOf(), 512);
strictEqual(+wrapped, 512);
strictEqual(wrapped.toString(), '512');
strictEqual('' + wrapped, '512');
});
}());
});

View File

@@ -1,35 +1,27 @@
(function() {
var _ = typeof require == 'function' ? require('..') : window._;
$(document).ready(function() {
QUnit.module('Collections');
module("Collections");
test('each', function() {
test("each", function() {
_.each([1, 2, 3], function(num, i) {
equal(num, i + 1, 'each iterators provide value and iteration count');
});
var answers = [];
_.each([1, 2, 3], function(num){ answers.push(num * this.multiplier);}, {multiplier : 5});
deepEqual(answers, [5, 10, 15], 'context object property accessed');
equal(answers.join(', '), '5, 10, 15', 'context object property accessed');
answers = [];
_.each([1, 2, 3], function(num){ answers.push(num); });
deepEqual(answers, [1, 2, 3], 'aliased as "forEach"');
_.forEach([1, 2, 3], function(num){ answers.push(num); });
equal(answers.join(', '), '1, 2, 3', 'aliased as "forEach"');
answers = [];
var obj = {one : 1, two : 2, three : 3};
obj.constructor.prototype.four = 4;
_.each(obj, function(value, key){ answers.push(key); });
deepEqual(answers, ['one', 'two', 'three'], 'iterating over objects works, and ignores the object prototype.');
equal(answers.join(", "), 'one, two, three', 'iterating over objects works, and ignores the object prototype.');
delete obj.constructor.prototype.four;
// ensure the each function is JITed
_(1000).times(function() { _.each([], function(){}); });
var count = 0;
obj = {1 : 'foo', 2 : 'bar', 3 : 'baz'};
_.each(obj, function(value, key){ count++; });
equal(count, 3, 'the fun should be called only 3 times');
var answer = null;
_.each([1, 2, 3], function(num, index, arr){ if (_.include(arr, num)) answer = true; });
ok(answer, 'can reference the original collection from inside the iterator');
@@ -37,142 +29,34 @@
answers = 0;
_.each(null, function(){ ++answers; });
equal(answers, 0, 'handles a null properly');
_.each(false, function(){});
var a = [1, 2, 3];
strictEqual(_.each(a, function(){}), a);
strictEqual(_.each(null, function(){}), null);
});
test('forEach', function() {
strictEqual(_.each, _.forEach, 'alias for each');
});
test('lookupIterator with contexts', function() {
_.each([true, false, 'yes', '', 0, 1, {}], function(context) {
_.each([1], function() {
equal(this, context);
}, context);
});
});
test('Iterating objects with sketchy length properties', function() {
var functions = [
'each', 'map', 'filter', 'find',
'some', 'every', 'max', 'min',
'groupBy', 'countBy', 'partition', 'indexBy'
];
var reducers = ['reduce', 'reduceRight'];
var tricks = [
{length: '5'},
{
length: {
valueOf: _.constant(5)
}
},
{length: Math.pow(2, 53) + 1},
{length: Math.pow(2, 53)},
{length: null},
{length: -2},
{length: new Number(15)}
];
expect(tricks.length * (functions.length + reducers.length + 4));
_.each(tricks, function(trick) {
var length = trick.length;
strictEqual(_.size(trick), 1, 'size on obj with length: ' + length);
deepEqual(_.toArray(trick), [length], 'toArray on obj with length: ' + length);
deepEqual(_.shuffle(trick), [length], 'shuffle on obj with length: ' + length);
deepEqual(_.sample(trick), length, 'sample on obj with length: ' + length);
_.each(functions, function(method) {
_[method](trick, function(val, key) {
strictEqual(key, 'length', method + ': ran with length = ' + val);
});
});
_.each(reducers, function(method) {
strictEqual(_[method](trick), trick.length, method);
});
});
});
test('Resistant to collection length and properties changing while iterating', function() {
var collection = [
'each', 'map', 'filter', 'find',
'some', 'every', 'max', 'min', 'reject',
'groupBy', 'countBy', 'partition', 'indexBy',
'reduce', 'reduceRight'
];
var array = [
'findIndex', 'findLastIndex'
];
var object = [
'mapObject', 'findKey', 'pick', 'omit'
];
_.each(collection.concat(array), function(method) {
var sparseArray = [1, 2, 3];
sparseArray.length = 100;
var answers = 0;
_[method](sparseArray, function(){
++answers;
return method === 'every' ? true : null;
}, {});
equal(answers, 100, method + ' enumerates [0, length)');
var growingCollection = [1, 2, 3], count = 0;
_[method](growingCollection, function() {
if (count < 10) growingCollection.push(count++);
return method === 'every' ? true : null;
}, {});
equal(count, 3, method + ' is resistant to length changes');
});
_.each(collection.concat(object), function(method) {
var changingObject = {0: 0, 1: 1}, count = 0;
_[method](changingObject, function(val) {
if (count < 10) changingObject[++count] = val + 1;
return method === 'every' ? true : null;
}, {});
equal(count, 2, method + ' is resistant to property changes');
});
});
test('map', function() {
var doubled = _.map([1, 2, 3], function(num){ return num * 2; });
deepEqual(doubled, [2, 4, 6], 'doubled numbers');
equal(doubled.join(', '), '2, 4, 6', 'doubled numbers');
doubled = _.collect([1, 2, 3], function(num){ return num * 2; });
equal(doubled.join(', '), '2, 4, 6', 'aliased as "collect"');
var tripled = _.map([1, 2, 3], function(num){ return num * this.multiplier; }, {multiplier : 3});
deepEqual(tripled, [3, 6, 9], 'tripled numbers with context');
equal(tripled.join(', '), '3, 6, 9', 'tripled numbers with context');
doubled = _([1, 2, 3]).map(function(num){ return num * 2; });
deepEqual(doubled, [2, 4, 6], 'OO-style doubled numbers');
var doubled = _([1, 2, 3]).map(function(num){ return num * 2; });
equal(doubled.join(', '), '2, 4, 6', 'OO-style doubled numbers');
var ids = _.map({length: 2, 0: {id: '1'}, 1: {id: '2'}}, function(n){
return n.id;
});
deepEqual(ids, ['1', '2'], 'Can use collection methods on Array-likes.');
if (document.querySelectorAll) {
var ids = _.map(document.querySelectorAll('#map-test *'), function(n){ return n.id; });
deepEqual(ids, ['id1', 'id2'], 'Can use collection methods on NodeLists.');
}
deepEqual(_.map(null, _.noop), [], 'handles a null properly');
var ids = _.map($('#map-test').children(), function(n){ return n.id; });
deepEqual(ids, ['id1', 'id2'], 'Can use collection methods on jQuery Array-likes.');
deepEqual(_.map([1], function() {
return this.length;
}, [5]), [1], 'called with context');
var ids = _.map(document.images, function(n){ return n.id; });
ok(ids[0] == 'chart_image', 'can use collection methods on HTMLCollections');
// Passing a property name like _.pluck.
var people = [{name : 'moe', age : 30}, {name : 'curly', age : 50}];
deepEqual(_.map(people, 'name'), ['moe', 'curly'], 'predicate string map to object properties');
});
test('collect', function() {
strictEqual(_.map, _.collect, 'alias for map');
var ifnull = _.map(null, function(){});
ok(_.isArray(ifnull) && ifnull.length === 0, 'handles a null properly');
});
test('reduce', function() {
@@ -189,37 +73,47 @@
sum = _([1, 2, 3]).reduce(function(sum, num){ return sum + num; }, 0);
equal(sum, 6, 'OO-style reduce');
sum = _.reduce([1, 2, 3], function(sum, num){ return sum + num; });
var sum = _.reduce([1, 2, 3], function(sum, num){ return sum + num; });
equal(sum, 6, 'default initial value');
var prod = _.reduce([1, 2, 3, 4], function(prod, num){ return prod * num; });
equal(prod, 24, 'can reduce via multiplication');
var ifnull;
try {
_.reduce(null, function(){});
} catch (ex) {
ifnull = ex;
}
ok(ifnull instanceof TypeError, 'handles a null (without inital value) properly');
ok(_.reduce(null, _.noop, 138) === 138, 'handles a null (with initial value) properly');
equal(_.reduce([], _.noop, undefined), undefined, 'undefined can be passed as a special case');
equal(_.reduce([_], _.noop), _, 'collection of length one with no initial value returns the first item');
equal(_.reduce([], _.noop), undefined, 'returns undefined when collection is empty and no initial value');
});
test('foldl', function() {
strictEqual(_.reduce, _.foldl, 'alias for reduce');
ok(_.reduce(null, function(){}, 138) === 138, 'handles a null (with initial value) properly');
equal(_.reduce([], function(){}, undefined), undefined, 'undefined can be passed as a special case');
raises(function() { _.reduce([], function(){}); }, TypeError, 'throws an error for empty arrays with no initial value');
});
test('reduceRight', function() {
var list = _.reduceRight(['foo', 'bar', 'baz'], function(memo, str){ return memo + str; }, '');
var list = _.reduceRight(["foo", "bar", "baz"], function(memo, str){ return memo + str; }, '');
equal(list, 'bazbarfoo', 'can perform right folds');
list = _.reduceRight(['foo', 'bar', 'baz'], function(memo, str){ return memo + str; });
var list = _.foldr(["foo", "bar", "baz"], function(memo, str){ return memo + str; }, '');
equal(list, 'bazbarfoo', 'aliased as "foldr"');
var list = _.foldr(["foo", "bar", "baz"], function(memo, str){ return memo + str; });
equal(list, 'bazbarfoo', 'default initial value');
var ifnull;
try {
_.reduceRight(null, function(){});
} catch (ex) {
ifnull = ex;
}
ok(ifnull instanceof TypeError, 'handles a null (without inital value) properly');
var sum = _.reduceRight({a: 1, b: 2, c: 3}, function(sum, num){ return sum + num; });
equal(sum, 6, 'default initial value on object');
ok(_.reduceRight(null, _.noop, 138) === 138, 'handles a null (with initial value) properly');
equal(_.reduceRight([_], _.noop), _, 'collection of length one with no initial value returns the first item');
ok(_.reduceRight(null, function(){}, 138) === 138, 'handles a null (with initial value) properly');
equal(_.reduceRight([], _.noop, undefined), undefined, 'undefined can be passed as a special case');
equal(_.reduceRight([], _.noop), undefined, 'returns undefined when collection is empty and no initial value');
equal(_.reduceRight([], function(){}, undefined), undefined, 'undefined can be passed as a special case');
raises(function() { _.reduceRight([], function(){}); }, TypeError, 'throws an error for empty arrays with no initial value');
// Assert that the correct arguments are being passed.
@@ -228,12 +122,12 @@
object = {a: 1, b: 2},
lastKey = _.keys(object).pop();
var expected = lastKey === 'a'
var expected = lastKey == 'a'
? [memo, 1, 'a', object]
: [memo, 2, 'b', object];
_.reduceRight(object, function() {
if (!args) args = _.toArray(arguments);
args || (args = _.toArray(arguments));
}, memo);
deepEqual(args, expected);
@@ -244,241 +138,96 @@
lastKey = _.keys(object).pop();
args = null;
expected = lastKey === '2'
expected = lastKey == '2'
? [memo, 'a', '2', object]
: [memo, 'b', '1', object];
_.reduceRight(object, function() {
if (!args) args = _.toArray(arguments);
args || (args = _.toArray(arguments));
}, memo);
deepEqual(args, expected);
});
test('foldr', function() {
strictEqual(_.reduceRight, _.foldr, 'alias for reduceRight');
});
test('find', function() {
var array = [1, 2, 3, 4];
strictEqual(_.find(array, function(n) { return n > 2; }), 3, 'should return first found `value`');
strictEqual(_.find(array, function() { return false; }), void 0, 'should return `undefined` if `value` is not found');
array.dontmatch = 55;
strictEqual(_.find(array, function(x) { return x === 55; }), void 0, 'iterates array-likes correctly');
// Matching an object like _.findWhere.
var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}, {a: 2, b: 4}];
deepEqual(_.find(list, {a: 1}), {a: 1, b: 2}, 'can be used as findWhere');
deepEqual(_.find(list, {b: 4}), {a: 1, b: 4});
ok(!_.find(list, {c: 1}), 'undefined when not found');
ok(!_.find([], {c: 1}), 'undefined when searching empty list');
var result = _.find([1, 2, 3], function(num){ return num * 2 === 4; });
equal(result, 2, 'found the first "2" and broke the loop');
var obj = {
a: {x: 1, z: 3},
b: {x: 2, z: 2},
c: {x: 3, z: 4},
d: {x: 4, z: 1}
};
deepEqual(_.find(obj, {x: 2}), {x: 2, z: 2}, 'works on objects');
deepEqual(_.find(obj, {x: 2, z: 1}), void 0);
deepEqual(_.find(obj, function(x) {
return x.x === 4;
}), {x: 4, z: 1});
_.findIndex([{a: 1}], function(a, key, obj) {
equal(key, 0);
deepEqual(obj, [{a: 1}]);
strictEqual(this, _, 'called with context');
}, _);
});
test('detect', function() {
strictEqual(_.detect, _.find, 'alias for detect');
});
test('filter', function() {
var evenArray = [1, 2, 3, 4, 5, 6];
var evenObject = {one: 1, two: 2, three: 3};
var isEven = function(num){ return num % 2 === 0; };
deepEqual(_.filter(evenArray, isEven), [2, 4, 6]);
deepEqual(_.filter(evenObject, isEven), [2], 'can filter objects');
deepEqual(_.filter([{}, evenObject, []], 'two'), [evenObject], 'predicate string map to object properties');
_.filter([1], function() {
equal(this, evenObject, 'given context');
}, evenObject);
// Can be used like _.where.
var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}];
deepEqual(_.filter(list, {a: 1}), [{a: 1, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}]);
deepEqual(_.filter(list, {b: 2}), [{a: 1, b: 2}, {a: 2, b: 2}]);
deepEqual(_.filter(list, {}), list, 'Empty object accepts all items');
deepEqual(_(list).filter({}), list, 'OO-filter');
var result = _.detect([1, 2, 3], function(num){ return num * 2 == 4; });
equal(result, 2, 'found the first "2" and broke the loop');
});
test('select', function() {
strictEqual(_.filter, _.select, 'alias for filter');
var evens = _.select([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
equal(evens.join(', '), '2, 4, 6', 'selected each even number');
evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
equal(evens.join(', '), '2, 4, 6', 'aliased as "filter"');
});
test('reject', function() {
var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 === 0; });
deepEqual(odds, [1, 3, 5], 'rejected each even number');
var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
equal(odds.join(', '), '1, 3, 5', 'rejected each even number');
var context = 'obj';
var context = "obj";
var evens = _.reject([1, 2, 3, 4, 5, 6], function(num){
equal(context, 'obj');
return num % 2 !== 0;
equal(context, "obj");
return num % 2 != 0;
}, context);
deepEqual(evens, [2, 4, 6], 'rejected each odd number');
deepEqual(_.reject([odds, {one: 1, two: 2, three: 3}], 'two'), [odds], 'predicate string map to object properties');
// Can be used like _.where.
var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}];
deepEqual(_.reject(list, {a: 1}), [{a: 2, b: 2}]);
deepEqual(_.reject(list, {b: 2}), [{a: 1, b: 3}, {a: 1, b: 4}]);
deepEqual(_.reject(list, {}), [], 'Returns empty list given empty object');
deepEqual(_.reject(list, []), [], 'Returns empty list given empty array');
});
test('every', function() {
ok(_.every([], _.identity), 'the empty set');
ok(_.every([true, true, true], _.identity), 'every true values');
ok(!_.every([true, false, true], _.identity), 'one false value');
ok(_.every([0, 10, 28], function(num){ return num % 2 === 0; }), 'even numbers');
ok(!_.every([0, 11, 28], function(num){ return num % 2 === 0; }), 'an odd number');
ok(_.every([1], _.identity) === true, 'cast to boolean - true');
ok(_.every([0], _.identity) === false, 'cast to boolean - false');
ok(!_.every([undefined, undefined, undefined], _.identity), 'works with arrays of undefined');
var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}];
ok(!_.every(list, {a: 1, b: 2}), 'Can be called with object');
ok(_.every(list, 'a'), 'String mapped to object property');
list = [{a: 1, b: 2}, {a: 2, b: 2, c: true}];
ok(_.every(list, {b: 2}), 'Can be called with object');
ok(!_.every(list, 'c'), 'String mapped to object property');
ok(_.every({a: 1, b: 2, c: 3, d: 4}, _.isNumber), 'takes objects');
ok(!_.every({a: 1, b: 2, c: 3, d: 4}, _.isObject), 'takes objects');
ok(_.every(['a', 'b', 'c', 'd'], _.hasOwnProperty, {a: 1, b: 2, c: 3, d: 4}), 'context works');
ok(!_.every(['a', 'b', 'c', 'd', 'f'], _.hasOwnProperty, {a: 1, b: 2, c: 3, d: 4}), 'context works');
equal(evens.join(', '), '2, 4, 6', 'rejected each odd number');
});
test('all', function() {
strictEqual(_.all, _.every, 'alias for all');
});
test('some', function() {
ok(!_.some([]), 'the empty set');
ok(!_.some([false, false, false]), 'all false values');
ok(_.some([false, false, true]), 'one true value');
ok(_.some([null, 0, 'yes', false]), 'a string');
ok(!_.some([null, 0, '', false]), 'falsy values');
ok(!_.some([1, 11, 29], function(num){ return num % 2 === 0; }), 'all odd numbers');
ok(_.some([1, 10, 29], function(num){ return num % 2 === 0; }), 'an even number');
ok(_.some([1], _.identity) === true, 'cast to boolean - true');
ok(_.some([0], _.identity) === false, 'cast to boolean - false');
ok(_.some([false, false, true]));
var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}];
ok(!_.some(list, {a: 5, b: 2}), 'Can be called with object');
ok(_.some(list, 'a'), 'String mapped to object property');
list = [{a: 1, b: 2}, {a: 2, b: 2, c: true}];
ok(_.some(list, {b: 2}), 'Can be called with object');
ok(!_.some(list, 'd'), 'String mapped to object property');
ok(_.some({a: '1', b: '2', c: '3', d: '4', e: 6}, _.isNumber), 'takes objects');
ok(!_.some({a: 1, b: 2, c: 3, d: 4}, _.isObject), 'takes objects');
ok(_.some(['a', 'b', 'c', 'd'], _.hasOwnProperty, {a: 1, b: 2, c: 3, d: 4}), 'context works');
ok(!_.some(['x', 'y', 'z'], _.hasOwnProperty, {a: 1, b: 2, c: 3, d: 4}), 'context works');
ok(_.all([], _.identity), 'the empty set');
ok(_.all([true, true, true], _.identity), 'all true values');
ok(!_.all([true, false, true], _.identity), 'one false value');
ok(_.all([0, 10, 28], function(num){ return num % 2 == 0; }), 'even numbers');
ok(!_.all([0, 11, 28], function(num){ return num % 2 == 0; }), 'an odd number');
ok(_.all([1], _.identity) === true, 'cast to boolean - true');
ok(_.all([0], _.identity) === false, 'cast to boolean - false');
ok(_.every([true, true, true], _.identity), 'aliased as "every"');
ok(!_.all([undefined, undefined, undefined], _.identity), 'works with arrays of undefined');
});
test('any', function() {
strictEqual(_.any, _.some, 'alias for any');
});
test('includes', function() {
_.each([null, void 0, 0, 1, NaN, {}, []], function(val) {
strictEqual(_.includes(val, 'hasOwnProperty'), false);
});
strictEqual(_.includes([1, 2, 3], 2), true, 'two is in the array');
ok(!_.includes([1, 3, 9], 2), 'two is not in the array');
strictEqual(_.includes([5, 4, 3, 2, 1], 5, true), true, 'doesn\'t delegate to binary search');
ok(_.includes({moe: 1, larry: 3, curly: 9}, 3) === true, '_.includes on objects checks their values');
ok(_([1, 2, 3]).includes(2), 'OO-style includes');
var nativeSome = Array.prototype.some;
Array.prototype.some = null;
ok(!_.any([]), 'the empty set');
ok(!_.any([false, false, false]), 'all false values');
ok(_.any([false, false, true]), 'one true value');
ok(_.any([null, 0, 'yes', false]), 'a string');
ok(!_.any([null, 0, '', false]), 'falsy values');
ok(!_.any([1, 11, 29], function(num){ return num % 2 == 0; }), 'all odd numbers');
ok(_.any([1, 10, 29], function(num){ return num % 2 == 0; }), 'an even number');
ok(_.any([1], _.identity) === true, 'cast to boolean - true');
ok(_.any([0], _.identity) === false, 'cast to boolean - false');
ok(_.some([false, false, true]), 'aliased as "some"');
Array.prototype.some = nativeSome;
});
test('include', function() {
strictEqual(_.includes, _.include, 'alias for includes');
ok(_.include([1,2,3], 2), 'two is in the array');
ok(!_.include([1,3,9], 2), 'two is not in the array');
ok(_.contains({moe:1, larry:3, curly:9}, 3) === true, '_.include on objects checks their values');
ok(_([1,2,3]).include(2), 'OO-style include');
});
test('contains', function() {
strictEqual(_.includes, _.contains, 'alias for includes');
var numbers = [1, 2, 3, 1, 2, 3, 1, 2, 3];
strictEqual(_.includes(numbers, 1, 1), true, 'contains takes a fromIndex');
strictEqual(_.includes(numbers, 1, -1), false, 'contains takes a fromIndex');
strictEqual(_.includes(numbers, 1, -2), false, 'contains takes a fromIndex');
strictEqual(_.includes(numbers, 1, -3), true, 'contains takes a fromIndex');
strictEqual(_.includes(numbers, 1, 6), true, 'contains takes a fromIndex');
strictEqual(_.includes(numbers, 1, 7), false, 'contains takes a fromIndex');
ok(_.every([1, 2, 3], _.partial(_.contains, numbers)), 'fromIndex is guarded');
});
test('includes with NaN', function() {
strictEqual(_.includes([1, 2, NaN, NaN], NaN), true, 'Expected [1, 2, NaN] to contain NaN');
strictEqual(_.includes([1, 2, Infinity], NaN), false, 'Expected [1, 2, NaN] to contain NaN');
});
test('includes with +- 0', function() {
_.each([-0, +0], function(val) {
strictEqual(_.includes([1, 2, val, val], val), true);
strictEqual(_.includes([1, 2, val, val], -val), true);
strictEqual(_.includes([-1, 1, 2], -val), false);
});
});
test('invoke', 5, function() {
test('invoke', function() {
var list = [[5, 1, 7], [3, 2, 1]];
var result = _.invoke(list, 'sort');
deepEqual(result[0], [1, 5, 7], 'first array sorted');
deepEqual(result[1], [1, 2, 3], 'second array sorted');
_.invoke([{
method: function() {
deepEqual(_.toArray(arguments), [1, 2, 3], 'called with arguments');
}
}], 'method', 1, 2, 3);
deepEqual(_.invoke([{a: null}, {}, {a: _.constant(1)}], 'a'), [null, void 0, 1], 'handles null & undefined');
throws(function() {
_.invoke([{a: 1}], 'a');
}, TypeError, 'throws for non-functions');
equal(result[0].join(', '), '1, 5, 7', 'first array sorted');
equal(result[1].join(', '), '1, 2, 3', 'second array sorted');
});
test('invoke w/ function reference', function() {
var list = [[5, 1, 7], [3, 2, 1]];
var result = _.invoke(list, Array.prototype.sort);
deepEqual(result[0], [1, 5, 7], 'first array sorted');
deepEqual(result[1], [1, 2, 3], 'second array sorted');
deepEqual(_.invoke([1, 2, 3], function(a) {
return a + this;
}, 5), [6, 7, 8], 'receives params from invoke');
equal(result[0].join(', '), '1, 5, 7', 'first array sorted');
equal(result[1].join(', '), '1, 2, 3', 'second array sorted');
});
// Relevant when using ClojureScript
@@ -487,21 +236,18 @@
return 42;
};
var list = [[5, 1, 7], [3, 2, 1]];
var s = 'foo';
equal(s.call(), 42, 'call function exists');
var s = "foo";
equal(s.call(), 42, "call function exists");
var result = _.invoke(list, 'sort');
deepEqual(result[0], [1, 5, 7], 'first array sorted');
deepEqual(result[1], [1, 2, 3], 'second array sorted');
equal(result[0].join(', '), '1, 5, 7', 'first array sorted');
equal(result[1].join(', '), '1, 2, 3', 'second array sorted');
delete String.prototype.call;
equal(s.call, undefined, 'call function removed');
equal(s.call, undefined, "call function removed");
});
test('pluck', function() {
var people = [{name: 'moe', age: 30}, {name: 'curly', age: 50}];
deepEqual(_.pluck(people, 'name'), ['moe', 'curly'], 'pulls names out of objects');
deepEqual(_.pluck(people, 'address'), [undefined, undefined], 'missing properties are returned as undefined');
//compat: most flexible handling of edge cases
deepEqual(_.pluck([{'[object Object]': 1}], {}), [1]);
var people = [{name : 'moe', age : 30}, {name : 'curly', age : 50}];
equal(_.pluck(people, 'name').join(', '), 'moe, curly', 'pulls names out of objects');
});
test('where', function() {
@@ -512,12 +258,6 @@
result = _.where(list, {b: 2});
equal(result.length, 2);
equal(result[0].a, 1);
result = _.where(list, {});
equal(result.length, list.length);
function test() {}
test.map = _.map;
deepEqual(_.where([_, {a: 1, b: 2}, _], test), [_, _], 'checks properties given function');
});
test('findWhere', function() {
@@ -526,30 +266,9 @@
deepEqual(result, {a: 1, b: 2});
result = _.findWhere(list, {b: 4});
deepEqual(result, {a: 1, b: 4});
result = _.findWhere(list, {c: 1});
ok(_.isUndefined(result), 'undefined when not found');
result = _.findWhere([], {c: 1});
ok(_.isUndefined(result), 'undefined when searching empty list');
function test() {}
test.map = _.map;
equal(_.findWhere([_, {a: 1, b: 2}, _], test), _, 'checks properties given function');
function TestClass() {
this.y = 5;
this.x = 'foo';
}
var expect = {c: 1, x: 'foo', y: 5};
deepEqual(_.findWhere([{y: 5, b: 6}, expect], new TestClass()), expect, 'uses class instance properties');
});
test('max', function() {
equal(-Infinity, _.max(null), 'can handle null/undefined');
equal(-Infinity, _.max(undefined), 'can handle null/undefined');
equal(-Infinity, _.max(null, _.identity), 'can handle null/undefined');
equal(3, _.max([1, 2, 3]), 'can perform a regular Math.max');
var neg = _.max([1, 2, 3], function(num){ return -num; });
@@ -559,28 +278,10 @@
equal(-Infinity, _.max([]), 'Maximum value of an empty array');
equal(_.max({'a': 'a'}), -Infinity, 'Maximum value of a non-numeric collection');
equal(299999, _.max(_.range(1, 300000)), 'Maximum value of a too-big array');
equal(3, _.max([1, 2, 3, 'test']), 'Finds correct max in array starting with num and containing a NaN');
equal(3, _.max(['test', 1, 2, 3]), 'Finds correct max in array starting with NaN');
var a = {x: -Infinity};
var b = {x: -Infinity};
var iterator = function(o){ return o.x; };
equal(_.max([a, b], iterator), a, 'Respects iterator return value of -Infinity');
deepEqual(_.max([{'a': 1}, {'a': 0, 'b': 3}, {'a': 4}, {'a': 2}], 'a'), {'a': 4}, 'String keys use property iterator');
deepEqual(_.max([0, 2], function(a){ return a * this.x; }, {x: 1}), 2, 'Iterator context');
deepEqual(_.max([[1], [2, 3], [-1, 4], [5]], 0), [5], 'Lookup falsy iterator');
deepEqual(_.max([{0: 1}, {0: 2}, {0: -1}, {a: 1}], 0), {0: 2}, 'Lookup falsy iterator');
equal(299999, _.max(_.range(1,300000)), "Maximum value of a too-big array");
});
test('min', function() {
equal(Infinity, _.min(null), 'can handle null/undefined');
equal(Infinity, _.min(undefined), 'can handle null/undefined');
equal(Infinity, _.min(null, _.identity), 'can handle null/undefined');
equal(1, _.min([1, 2, 3]), 'can perform a regular Math.min');
var neg = _.min([1, 2, 3], function(num){ return -num; });
@@ -594,34 +295,20 @@
var then = new Date(0);
equal(_.min([now, then]), then);
equal(1, _.min(_.range(1, 300000)), 'Minimum value of a too-big array');
equal(1, _.min([1, 2, 3, 'test']), 'Finds correct min in array starting with num and containing a NaN');
equal(1, _.min(['test', 1, 2, 3]), 'Finds correct min in array starting with NaN');
var a = {x: Infinity};
var b = {x: Infinity};
var iterator = function(o){ return o.x; };
equal(_.min([a, b], iterator), a, 'Respects iterator return value of Infinity');
deepEqual(_.min([{'a': 1}, {'a': 0, 'b': 3}, {'a': 4}, {'a': 2}], 'a'), {'a': 0, 'b': 3}, 'String keys use property iterator');
deepEqual(_.min([0, 2], function(a){ return a * this.x; }, {x: -1}), 2, 'Iterator context');
deepEqual(_.min([[1], [2, 3], [-1, 4], [5]], 0), [-1, 4], 'Lookup falsy iterator');
deepEqual(_.min([{0: 1}, {0: 2}, {0: -1}, {a: 1}], 0), {0: -1}, 'Lookup falsy iterator');
equal(1, _.min(_.range(1,300000)), "Minimum value of a too-big array");
});
test('sortBy', function() {
var people = [{name : 'curly', age : 50}, {name : 'moe', age : 30}];
people = _.sortBy(people, function(person){ return person.age; });
deepEqual(_.pluck(people, 'name'), ['moe', 'curly'], 'stooges sorted by age');
equal(_.pluck(people, 'name').join(', '), 'moe, curly', 'stooges sorted by age');
var list = [undefined, 4, 1, undefined, 3, 2];
deepEqual(_.sortBy(list, _.identity), [1, 2, 3, 4, undefined, undefined], 'sortBy with undefined values');
equal(_.sortBy(list, _.identity).join(','), '1,2,3,4,,', 'sortBy with undefined values');
list = ['one', 'two', 'three', 'four', 'five'];
var list = ["one", "two", "three", "four", "five"];
var sorted = _.sortBy(list, 'length');
deepEqual(sorted, ['one', 'two', 'four', 'five', 'three'], 'sorted by length');
equal(sorted.join(' '), 'one two four five three', 'sorted by length');
function Pair(x, y) {
this.x = x;
@@ -645,23 +332,18 @@
});
deepEqual(actual, collection, 'sortBy should be stable');
deepEqual(_.sortBy(collection, 'x'), collection, 'sortBy accepts property string');
list = ['q', 'w', 'e', 'r', 't', 'y'];
deepEqual(_.sortBy(list), ['e', 'q', 'r', 't', 'w', 'y'], 'uses _.identity if iterator is not specified');
});
test('groupBy', function() {
var parity = _.groupBy([1, 2, 3, 4, 5, 6], function(num){ return num % 2; });
ok('0' in parity && '1' in parity, 'created a group for each value');
deepEqual(parity[0], [2, 4, 6], 'put each even number in the right group');
equal(parity[0].join(', '), '2, 4, 6', 'put each even number in the right group');
var list = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'];
var list = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"];
var grouped = _.groupBy(list, 'length');
deepEqual(grouped['3'], ['one', 'two', 'six', 'ten']);
deepEqual(grouped['4'], ['four', 'five', 'nine']);
deepEqual(grouped['5'], ['three', 'seven', 'eight']);
equal(grouped['3'].join(' '), 'one two six ten');
equal(grouped['4'].join(' '), 'four five nine');
equal(grouped['5'].join(' '), 'three seven eight');
var context = {};
_.groupBy([{}], function(){ ok(this === context); }, context);
@@ -675,44 +357,18 @@
var array = [{}];
_.groupBy(array, function(value, index, obj){ ok(obj === array); });
array = [1, 2, 1, 2, 3];
grouped = _.groupBy(array);
var array = [1, 2, 1, 2, 3];
var grouped = _.groupBy(array);
equal(grouped['1'].length, 2);
equal(grouped['3'].length, 1);
var matrix = [
[1, 2],
[1, 3],
[2, 3]
];
deepEqual(_.groupBy(matrix, 0), {1: [[1, 2], [1, 3]], 2: [[2, 3]]});
deepEqual(_.groupBy(matrix, 1), {2: [[1, 2]], 3: [[1, 3], [2, 3]]});
});
test('indexBy', function() {
var parity = _.indexBy([1, 2, 3, 4, 5], function(num){ return num % 2 === 0; });
equal(parity['true'], 4);
equal(parity['false'], 5);
var list = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'];
var grouped = _.indexBy(list, 'length');
equal(grouped['3'], 'ten');
equal(grouped['4'], 'nine');
equal(grouped['5'], 'eight');
var array = [1, 2, 1, 2, 3];
grouped = _.indexBy(array);
equal(grouped['1'], 1);
equal(grouped['2'], 2);
equal(grouped['3'], 3);
});
test('countBy', function() {
var parity = _.countBy([1, 2, 3, 4, 5], function(num){ return num % 2 === 0; });
var parity = _.countBy([1, 2, 3, 4, 5], function(num){ return num % 2 == 0; });
equal(parity['true'], 2);
equal(parity['false'], 3);
var list = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'];
var list = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"];
var grouped = _.countBy(list, 'length');
equal(grouped['3'], 4);
equal(grouped['4'], 3);
@@ -730,63 +386,58 @@
var array = [{}];
_.countBy(array, function(value, index, obj){ ok(obj === array); });
array = [1, 2, 1, 2, 3];
grouped = _.countBy(array);
var array = [1, 2, 1, 2, 3];
var grouped = _.countBy(array);
equal(grouped['1'], 2);
equal(grouped['3'], 1);
});
test('shuffle', function() {
var numbers = _.range(10);
var shuffled = _.shuffle(numbers);
notStrictEqual(numbers, shuffled, 'original object is unmodified');
ok(_.every(_.range(10), function() { //appears consistent?
return _.every(numbers, _.partial(_.contains, numbers));
}), 'contains the same members before and after shuffle');
test('sortedIndex', function() {
var numbers = [10, 20, 30, 40, 50], num = 35;
var indexForNum = _.sortedIndex(numbers, num);
equal(indexForNum, 3, '35 should be inserted at index 3');
shuffled = _.shuffle({a: 1, b: 2, c: 3, d: 4});
equal(shuffled.length, 4);
deepEqual(shuffled.sort(), [1, 2, 3, 4], 'works on objects');
var indexFor30 = _.sortedIndex(numbers, 30);
equal(indexFor30, 2, '30 should be inserted at index 2');
var objects = [{x: 10}, {x: 20}, {x: 30}, {x: 40}];
var iterator = function(obj){ return obj.x; };
strictEqual(_.sortedIndex(objects, {x: 25}, iterator), 2);
strictEqual(_.sortedIndex(objects, {x: 35}, 'x'), 3);
var context = {1: 2, 2: 3, 3: 4};
iterator = function(obj){ return this[obj]; };
strictEqual(_.sortedIndex([1, 3], 2, iterator, context), 1);
});
test('sample', function() {
test('shuffle', function() {
var numbers = _.range(10);
var allSampled = _.sample(numbers, 10).sort();
deepEqual(allSampled, numbers, 'contains the same members before and after sample');
allSampled = _.sample(numbers, 20).sort();
deepEqual(allSampled, numbers, 'also works when sampling more objects than are present');
ok(_.contains(numbers, _.sample(numbers)), 'sampling a single element returns something from the array');
strictEqual(_.sample([]), undefined, 'sampling empty array with no number returns undefined');
notStrictEqual(_.sample([], 5), [], 'sampling empty array with a number returns an empty array');
notStrictEqual(_.sample([1, 2, 3], 0), [], 'sampling an array with 0 picks returns an empty array');
deepEqual(_.sample([1, 2], -1), [], 'sampling a negative number of picks returns an empty array');
ok(_.contains([1, 2, 3], _.sample({a: 1, b: 2, c: 3})), 'sample one value from an object');
var shuffled = _.shuffle(numbers).sort();
notStrictEqual(numbers, shuffled, 'original object is unmodified');
equal(shuffled.join(','), numbers.join(','), 'contains the same members before and after shuffle');
});
test('toArray', function() {
ok(!_.isArray(arguments), 'arguments object is not an array');
ok(_.isArray(_.toArray(arguments)), 'arguments object converted into array');
var a = [1, 2, 3];
var a = [1,2,3];
ok(_.toArray(a) !== a, 'array is cloned');
deepEqual(_.toArray(a), [1, 2, 3], 'cloned array contains same elements');
equal(_.toArray(a).join(', '), '1, 2, 3', 'cloned array contains same elements');
var numbers = _.toArray({one : 1, two : 2, three : 3});
deepEqual(numbers, [1, 2, 3], 'object flattened into array');
equal(numbers.join(', '), '1, 2, 3', 'object flattened into array');
if (typeof document != 'undefined') {
// test in IE < 9
var actual;
try {
actual = _.toArray(document.childNodes);
} catch(ex) { }
deepEqual(actual, _.map(document.childNodes, _.identity), 'works on NodeList');
}
// test in IE < 9
try {
var actual = _.toArray(document.childNodes);
} catch(ex) { }
ok(_.isArray(actual), 'should not throw converting a node list');
});
test('size', function() {
equal(_.size({one : 1, two : 2, three : 3}), 3, 'can compute the size of an object');
equal(_.size([1, 2, 3]), 3, 'can compute the size of an array');
equal(_.size({length: 3, 0: 0, 1: 0, 2: 0}), 3, 'can compute the size of Array-likes');
var func = function() {
return _.size(arguments);
@@ -794,64 +445,9 @@
equal(func(1, 2, 3, 4), 4, 'can test the size of the arguments object');
equal(_.size('hello'), 5, 'can compute the size of a string literal');
equal(_.size(new String('hello')), 5, 'can compute the size of string object');
equal(_.size('hello'), 5, 'can compute the size of a string');
equal(_.size(null), 0, 'handles nulls');
equal(_.size(0), 0, 'handles numbers');
});
test('partition', function() {
var list = [0, 1, 2, 3, 4, 5];
deepEqual(_.partition(list, function(x) { return x < 4; }), [[0, 1, 2, 3], [4, 5]], 'handles bool return values');
deepEqual(_.partition(list, function(x) { return x & 1; }), [[1, 3, 5], [0, 2, 4]], 'handles 0 and 1 return values');
deepEqual(_.partition(list, function(x) { return x - 3; }), [[0, 1, 2, 4, 5], [3]], 'handles other numeric return values');
deepEqual(_.partition(list, function(x) { return x > 1 ? null : true; }), [[0, 1], [2, 3, 4, 5]], 'handles null return values');
deepEqual(_.partition(list, function(x) { if (x < 2) return true; }), [[0, 1], [2, 3, 4, 5]], 'handles undefined return values');
deepEqual(_.partition({a: 1, b: 2, c: 3}, function(x) { return x > 1; }), [[2, 3], [1]], 'handles objects');
deepEqual(_.partition(list, function(x, index) { return index % 2; }), [[1, 3, 5], [0, 2, 4]], 'can reference the array index');
deepEqual(_.partition(list, function(x, index, arr) { return x === arr.length - 1; }), [[5], [0, 1, 2, 3, 4]], 'can reference the collection');
// Default iterator
deepEqual(_.partition([1, false, true, '']), [[1, true], [false, '']], 'Default iterator');
deepEqual(_.partition([{x: 1}, {x: 0}, {x: 1}], 'x'), [[{x: 1}, {x: 1}], [{x: 0}]], 'Takes a string');
// Context
var predicate = function(x){ return x === this.x; };
deepEqual(_.partition([1, 2, 3], predicate, {x: 2}), [[2], [1, 3]], 'partition takes a context argument');
deepEqual(_.partition([{a: 1}, {b: 2}, {a: 1, b: 2}], {a: 1}), [[{a: 1}, {a: 1, b: 2}], [{b: 2}]], 'predicate can be object');
var object = {a: 1};
_.partition(object, function(val, key, obj) {
equal(val, 1);
equal(key, 'a');
equal(obj, object);
equal(this, predicate);
}, predicate);
});
if (typeof document != 'undefined') {
test('Can use various collection methods on NodeLists', function() {
var parent = document.createElement('div');
parent.innerHTML = '<span id=id1></span>textnode<span id=id2></span>';
var elementChildren = _.filter(parent.childNodes, _.isElement);
equal(elementChildren.length, 2);
deepEqual(_.map(elementChildren, 'id'), ['id1', 'id2']);
deepEqual(_.map(parent.childNodes, 'nodeType'), [1, 3, 1]);
ok(!_.every(parent.childNodes, _.isElement));
ok(_.some(parent.childNodes, _.isElement));
function compareNode(node) {
return _.isElement(node) ? node.id.charAt(2) : void 0;
}
equal(_.max(parent.childNodes, compareNode), _.last(parent.childNodes));
equal(_.min(parent.childNodes, compareNode), _.first(parent.childNodes));
});
}
}());
});

View File

@@ -1,12 +1,10 @@
(function() {
var _ = typeof require == 'function' ? require('..') : window._;
$(document).ready(function() {
QUnit.module('Functions');
QUnit.config.asyncRetries = 3;
module("Functions");
test('bind', function() {
test("bind", function() {
var context = {name : 'moe'};
var func = function(arg) { return 'name: ' + (this.name || arg); };
var func = function(arg) { return "name: " + (this.name || arg); };
var bound = _.bind(func, context);
equal(bound(), 'name: moe', 'can bind a function to a context');
@@ -14,9 +12,7 @@
equal(bound(), 'name: moe', 'can do OO-style binding');
bound = _.bind(func, null, 'curly');
var result = bound();
// Work around a PhantomJS bug when applying a function with null|undefined.
ok(result === 'name: curly' || result === 'name: ' + window.name, 'can bind without specifying a context');
equal(bound(), 'name: curly', 'can bind without specifying a context');
func = function(salutation, name) { return salutation + ': ' + name; };
func = _.bind(func, this, 'hello');
@@ -37,49 +33,19 @@
// These tests are only meaningful when using a browser without a native bind function
// To test this with a modern browser, set underscore's nativeBind to undefined
var F = function () { return this; };
var boundf = _.bind(F, {hello: 'moe curly'});
var Boundf = boundf; // make eslint happy.
var newBoundf = new Boundf();
equal(newBoundf.hello, undefined, 'function should not be bound to the context, to comply with ECMAScript 5');
equal(boundf().hello, 'moe curly', "When called without the new operator, it's OK to be bound to the context");
ok(newBoundf instanceof F, 'a bound instance is an instance of the original function');
throws(function() { _.bind('notafunction'); }, TypeError, 'throws an error when binding to a non-function');
var Boundf = _.bind(F, {hello: "moe curly"});
equal(Boundf().hello, "moe curly", "When called without the new operator, it's OK to be bound to the context");
});
test('partial', function() {
test("partial", function() {
var obj = {name: 'moe'};
var func = function() { return this.name + ' ' + _.toArray(arguments).join(' '); };
obj.func = _.partial(func, 'a', 'b');
equal(obj.func('c', 'd'), 'moe a b c d', 'can partially apply');
obj.func = _.partial(func, _, 'b', _, 'd');
equal(obj.func('a', 'c'), 'moe a b c d', 'can partially apply with placeholders');
func = _.partial(function() { return arguments.length; }, _, 'b', _, 'd');
equal(func('a', 'c', 'e'), 5, 'accepts more arguments than the number of placeholders');
equal(func('a'), 4, 'accepts fewer arguments than the number of placeholders');
func = _.partial(function() { return typeof arguments[2]; }, _, 'b', _, 'd');
equal(func('a'), 'undefined', 'unfilled placeholders are undefined');
// passes context
function MyWidget(name, options) {
this.name = name;
this.options = options;
}
MyWidget.prototype.get = function() {
return this.name;
};
var MyWidgetWithCoolOpts = _.partial(MyWidget, _, {a: 1});
var widget = new MyWidgetWithCoolOpts('foo');
ok(widget instanceof MyWidget, 'Can partially bind a constructor');
equal(widget.get(), 'foo', 'keeps prototype');
deepEqual(widget.options, {a: 1});
});
test('bindAll', function() {
test("bindAll", function() {
var curly = {name : 'curly'}, moe = {
name : 'moe',
getName : function() { return 'name: ' + this.name; },
@@ -95,29 +61,20 @@
moe = {
name : 'moe',
getName : function() { return 'name: ' + this.name; },
sayHi : function() { return 'hi: ' + this.name; },
sayLast : function() { return this.sayHi(_.last(arguments)); }
sayHi : function() { return 'hi: ' + this.name; }
};
throws(function() { _.bindAll(moe); }, Error, 'throws an error for bindAll with no functions named');
throws(function() { _.bindAll(moe, 'sayBye'); }, TypeError, 'throws an error for bindAll if the given key is undefined');
throws(function() { _.bindAll(moe, 'name'); }, TypeError, 'throws an error for bindAll if the given key is not a function');
_.bindAll(moe, 'sayHi', 'sayLast');
_.bindAll(moe);
curly.sayHi = moe.sayHi;
equal(curly.sayHi(), 'hi: moe');
var sayLast = moe.sayLast;
equal(sayLast(1, 2, 3, 4, 5, 6, 7, 'Tom'), 'hi: moe', 'createCallback works with any number of arguments');
equal(curly.sayHi(), 'hi: moe', 'calling bindAll with no arguments binds all functions to the object');
});
test('memoize', function() {
test("memoize", function() {
var fib = function(n) {
return n < 2 ? n : fib(n - 1) + fib(n - 2);
};
var fastFib = _.memoize(fib);
equal(fib(10), 55, 'a memoized version of fibonacci produces identical results');
fib = _.memoize(fib); // Redefine `fib` for memoization
equal(fib(10), 55, 'a memoized version of fibonacci produces identical results');
equal(fastFib(10), 55, 'a memoized version of fibonacci produces identical results');
var o = function(str) {
return str;
@@ -125,137 +82,90 @@
var fastO = _.memoize(o);
equal(o('toString'), 'toString', 'checks hasOwnProperty');
equal(fastO('toString'), 'toString', 'checks hasOwnProperty');
// Expose the cache.
var upper = _.memoize(function(s) {
return s.toUpperCase();
});
equal(upper('foo'), 'FOO');
equal(upper('bar'), 'BAR');
deepEqual(upper.cache, {foo: 'FOO', bar: 'BAR'});
upper.cache = {foo: 'BAR', bar: 'FOO'};
equal(upper('foo'), 'BAR');
equal(upper('bar'), 'FOO');
var hashed = _.memoize(function(key) {
//https://github.com/jashkenas/underscore/pull/1679#discussion_r13736209
ok(/[a-z]+/.test(key), 'hasher doesn\'t change keys');
return key;
}, function(key) {
return key.toUpperCase();
});
hashed('yep');
deepEqual(hashed.cache, {'YEP': 'yep'}, 'takes a hasher');
// Test that the hash function can be used to swizzle the key.
var objCacher = _.memoize(function(value, key) {
return {key: key, value: value};
}, function(value, key) {
return key;
});
var myObj = objCacher('a', 'alpha');
var myObjAlias = objCacher('b', 'alpha');
notStrictEqual(myObj, undefined, 'object is created if second argument used as key');
strictEqual(myObj, myObjAlias, 'object is cached if second argument used as key');
strictEqual(myObj.value, 'a', 'object is not modified if second argument used as key');
});
asyncTest('delay', 2, function() {
asyncTest("delay", 2, function() {
var delayed = false;
_.delay(function(){ delayed = true; }, 100);
setTimeout(function(){ ok(!delayed, "didn't delay the function quite yet"); }, 50);
setTimeout(function(){ ok(delayed, 'delayed the function'); start(); }, 150);
});
asyncTest('defer', 1, function() {
asyncTest("defer", 1, function() {
var deferred = false;
_.defer(function(bool){ deferred = bool; }, true);
_.delay(function(){ ok(deferred, 'deferred the function'); start(); }, 50);
_.delay(function(){ ok(deferred, "deferred the function"); start(); }, 50);
});
asyncTest('throttle', 2, function() {
asyncTest("throttle", 2, function() {
var counter = 0;
var incr = function(){ counter++; };
var throttledIncr = _.throttle(incr, 32);
throttledIncr(); throttledIncr();
equal(counter, 1, 'incr was called immediately');
_.delay(function(){ equal(counter, 2, 'incr was throttled'); start(); }, 64);
equal(counter, 1, "incr was called immediately");
_.delay(function(){ equal(counter, 2, "incr was throttled"); start(); }, 64);
});
asyncTest('throttle arguments', 2, function() {
asyncTest("throttle arguments", 2, function() {
var value = 0;
var update = function(val){ value = val; };
var throttledUpdate = _.throttle(update, 32);
throttledUpdate(1); throttledUpdate(2);
_.delay(function(){ throttledUpdate(3); }, 64);
equal(value, 1, 'updated to latest value');
_.delay(function(){ equal(value, 3, 'updated to latest value'); start(); }, 96);
equal(value, 1, "updated to latest value");
_.delay(function(){ equal(value, 3, "updated to latest value"); start(); }, 96);
});
asyncTest('throttle once', 2, function() {
asyncTest("throttle once", 2, function() {
var counter = 0;
var incr = function(){ return ++counter; };
var throttledIncr = _.throttle(incr, 32);
var result = throttledIncr();
_.delay(function(){
equal(result, 1, 'throttled functions return their value');
equal(counter, 1, 'incr was called once'); start();
equal(result, 1, "throttled functions return their value");
equal(counter, 1, "incr was called once"); start();
}, 64);
});
asyncTest('throttle twice', 1, function() {
asyncTest("throttle twice", 1, function() {
var counter = 0;
var incr = function(){ counter++; };
var throttledIncr = _.throttle(incr, 32);
throttledIncr(); throttledIncr();
_.delay(function(){ equal(counter, 2, 'incr was called twice'); start(); }, 64);
_.delay(function(){ equal(counter, 2, "incr was called twice"); start(); }, 64);
});
asyncTest('more throttling', 3, function() {
var counter = 0;
var incr = function(){ counter++; };
var throttledIncr = _.throttle(incr, 30);
throttledIncr(); throttledIncr();
equal(counter, 1);
_.delay(function(){
equal(counter, 2);
throttledIncr();
equal(counter, 3);
start();
}, 85);
});
asyncTest('throttle repeatedly with results', 6, function() {
asyncTest("throttle repeatedly with results", 6, function() {
var counter = 0;
var incr = function(){ return ++counter; };
var throttledIncr = _.throttle(incr, 100);
var throttledIncr = _.throttle(incr, 64);
var results = [];
var saveResult = function() { results.push(throttledIncr()); };
saveResult(); saveResult();
_.delay(saveResult, 50);
_.delay(saveResult, 150);
_.delay(saveResult, 160);
_.delay(saveResult, 230);
_.delay(saveResult, 32);
_.delay(saveResult, 80);
_.delay(saveResult, 96);
_.delay(saveResult, 144);
_.delay(function() {
equal(results[0], 1, 'incr was called once');
equal(results[1], 1, 'incr was throttled');
equal(results[2], 1, 'incr was throttled');
equal(results[3], 2, 'incr was called twice');
equal(results[4], 2, 'incr was throttled');
equal(results[5], 3, 'incr was called trailing');
equal(results[0], 1, "incr was called once");
equal(results[1], 1, "incr was throttled");
equal(results[2], 1, "incr was throttled");
equal(results[3], 2, "incr was called twice");
equal(results[4], 2, "incr was throttled");
equal(results[5], 3, "incr was called trailing");
start();
}, 300);
}, 192);
});
asyncTest('throttle triggers trailing call when invoked repeatedly', 2, function() {
asyncTest("throttle triggers trailing call when invoked repeatedly", 2, function() {
var counter = 0;
var limit = 48;
var incr = function(){ counter++; };
var throttledIncr = _.throttle(incr, 32);
var stamp = new Date;
while (new Date - stamp < limit) {
while ((new Date - stamp) < limit) {
throttledIncr();
}
var lastCount = counter;
@@ -267,130 +177,16 @@
}, 96);
});
asyncTest('throttle does not trigger leading call when leading is set to false', 2, function() {
var counter = 0;
var incr = function(){ counter++; };
var throttledIncr = _.throttle(incr, 60, {leading: false});
throttledIncr(); throttledIncr();
equal(counter, 0);
_.delay(function() {
equal(counter, 1);
start();
}, 96);
});
asyncTest('more throttle does not trigger leading call when leading is set to false', 3, function() {
var counter = 0;
var incr = function(){ counter++; };
var throttledIncr = _.throttle(incr, 100, {leading: false});
throttledIncr();
_.delay(throttledIncr, 50);
_.delay(throttledIncr, 60);
_.delay(throttledIncr, 200);
equal(counter, 0);
_.delay(function() {
equal(counter, 1);
}, 250);
_.delay(function() {
equal(counter, 2);
start();
}, 350);
});
asyncTest('one more throttle with leading: false test', 2, function() {
var counter = 0;
var incr = function(){ counter++; };
var throttledIncr = _.throttle(incr, 100, {leading: false});
var time = new Date;
while (new Date - time < 350) throttledIncr();
ok(counter <= 3);
_.delay(function() {
ok(counter <= 4);
start();
}, 200);
});
asyncTest('throttle does not trigger trailing call when trailing is set to false', 4, function() {
var counter = 0;
var incr = function(){ counter++; };
var throttledIncr = _.throttle(incr, 60, {trailing: false});
throttledIncr(); throttledIncr(); throttledIncr();
equal(counter, 1);
_.delay(function() {
equal(counter, 1);
throttledIncr(); throttledIncr();
equal(counter, 2);
_.delay(function() {
equal(counter, 2);
start();
}, 96);
}, 96);
});
asyncTest('throttle continues to function after system time is set backwards', 2, function() {
var counter = 0;
var incr = function(){ counter++; };
var throttledIncr = _.throttle(incr, 100);
var origNowFunc = _.now;
throttledIncr();
equal(counter, 1);
_.now = function () {
return new Date(2013, 0, 1, 1, 1, 1);
};
_.delay(function() {
throttledIncr();
equal(counter, 2);
start();
_.now = origNowFunc;
}, 200);
});
asyncTest('throttle re-entrant', 2, function() {
var sequence = [
['b1', 'b2'],
['c1', 'c2']
];
var value = '';
var throttledAppend;
var append = function(arg){
value += this + arg;
var args = sequence.pop();
if (args) {
throttledAppend.call(args[0], args[1]);
}
};
throttledAppend = _.throttle(append, 32);
throttledAppend.call('a1', 'a2');
equal(value, 'a1a2');
_.delay(function(){
equal(value, 'a1a2c1c2b1b2', 'append was throttled successfully');
start();
}, 100);
});
asyncTest('debounce', 1, function() {
asyncTest("debounce", 1, function() {
var counter = 0;
var incr = function(){ counter++; };
var debouncedIncr = _.debounce(incr, 32);
debouncedIncr(); debouncedIncr();
_.delay(debouncedIncr, 16);
_.delay(function(){ equal(counter, 1, 'incr was debounced'); start(); }, 96);
_.delay(function(){ equal(counter, 1, "incr was debounced"); start(); }, 96);
});
asyncTest('debounce asap', 4, function() {
asyncTest("debounce asap", 4, function() {
var a, b;
var counter = 0;
var incr = function(){ return ++counter; };
@@ -403,131 +199,55 @@
_.delay(debouncedIncr, 16);
_.delay(debouncedIncr, 32);
_.delay(debouncedIncr, 48);
_.delay(function(){ equal(counter, 1, 'incr was debounced'); start(); }, 128);
_.delay(function(){ equal(counter, 1, "incr was debounced"); start(); }, 128);
});
asyncTest('debounce asap recursively', 2, function() {
asyncTest("debounce asap recursively", 2, function() {
var counter = 0;
var debouncedIncr = _.debounce(function(){
counter++;
if (counter < 10) debouncedIncr();
}, 32, true);
debouncedIncr();
equal(counter, 1, 'incr was called immediately');
_.delay(function(){ equal(counter, 1, 'incr was debounced'); start(); }, 96);
equal(counter, 1, "incr was called immediately");
_.delay(function(){ equal(counter, 1, "incr was debounced"); start(); }, 96);
});
asyncTest('debounce after system time is set backwards', 2, function() {
var counter = 0;
var origNowFunc = _.now;
var debouncedIncr = _.debounce(function(){
counter++;
}, 100, true);
debouncedIncr();
equal(counter, 1, 'incr was called immediately');
_.now = function () {
return new Date(2013, 0, 1, 1, 1, 1);
};
_.delay(function() {
debouncedIncr();
equal(counter, 2, 'incr was debounced successfully');
start();
_.now = origNowFunc;
}, 200);
});
asyncTest('debounce re-entrant', 2, function() {
var sequence = [
['b1', 'b2']
];
var value = '';
var debouncedAppend;
var append = function(arg){
value += this + arg;
var args = sequence.pop();
if (args) {
debouncedAppend.call(args[0], args[1]);
}
};
debouncedAppend = _.debounce(append, 32);
debouncedAppend.call('a1', 'a2');
equal(value, '');
_.delay(function(){
equal(value, 'a1a2b1b2', 'append was debounced successfully');
start();
}, 100);
});
test('once', function() {
test("once", function() {
var num = 0;
var increment = _.once(function(){ return ++num; });
var increment = _.once(function(){ num++; });
increment();
increment();
equal(num, 1);
equal(increment(), 1, 'stores a memo to the last value');
});
test('Recursive onced function.', 1, function() {
var f = _.once(function(){
ok(true);
f();
});
f();
});
test('wrap', function() {
var greet = function(name){ return 'hi: ' + name; };
test("wrap", function() {
var greet = function(name){ return "hi: " + name; };
var backwards = _.wrap(greet, function(func, name){ return func(name) + ' ' + name.split('').reverse().join(''); });
equal(backwards('moe'), 'hi: moe eom', 'wrapped the salutation function');
equal(backwards('moe'), 'hi: moe eom', 'wrapped the saluation function');
var inner = function(){ return 'Hello '; };
var obj = {name : 'Moe'};
var inner = function(){ return "Hello "; };
var obj = {name : "Moe"};
obj.hi = _.wrap(inner, function(fn){ return fn() + this.name; });
equal(obj.hi(), 'Hello Moe');
equal(obj.hi(), "Hello Moe");
var noop = function(){};
var wrapped = _.wrap(noop, function(){ return Array.prototype.slice.call(arguments, 0); });
var wrapped = _.wrap(noop, function(fn){ return Array.prototype.slice.call(arguments, 0); });
var ret = wrapped(['whats', 'your'], 'vector', 'victor');
deepEqual(ret, [noop, ['whats', 'your'], 'vector', 'victor']);
});
test('negate', function() {
var isOdd = function(n){ return n & 1; };
equal(_.negate(isOdd)(2), true, 'should return the complement of the given function');
equal(_.negate(isOdd)(3), false, 'should return the complement of the given function');
});
test('compose', function() {
var greet = function(name){ return 'hi: ' + name; };
test("compose", function() {
var greet = function(name){ return "hi: " + name; };
var exclaim = function(sentence){ return sentence + '!'; };
var composed = _.compose(exclaim, greet);
equal(composed('moe'), 'hi: moe!', 'can compose a function that takes another');
composed = _.compose(greet, exclaim);
equal(composed('moe'), 'hi: moe!', 'in this case, the functions are also commutative');
// f(g(h(x, y, z)))
function h(x, y, z) {
equal(arguments.length, 3, 'First function called with multiple args');
return z * y;
}
function g(x) {
equal(arguments.length, 1, 'Composed function is called with 1 argument');
return x;
}
function f(x) {
equal(arguments.length, 1, 'Composed function is called with 1 argument');
return x * 2;
}
composed = _.compose(f, g, h);
equal(composed(1, 2, 3), 12);
});
test('after', function() {
test("after", function() {
var testAfter = function(afterAmount, timesCalled) {
var afterCalled = 0;
var after = _.after(afterAmount, function() {
@@ -537,45 +257,9 @@
return afterCalled;
};
equal(testAfter(5, 5), 1, 'after(N) should fire after being called N times');
equal(testAfter(5, 4), 0, 'after(N) should not fire unless called N times');
equal(testAfter(0, 0), 0, 'after(0) should not fire immediately');
equal(testAfter(0, 1), 1, 'after(0) should fire when first invoked');
equal(testAfter(5, 5), 1, "after(N) should fire after being called N times");
equal(testAfter(5, 4), 0, "after(N) should not fire unless called N times");
equal(testAfter(0, 0), 1, "after(0) should fire immediately");
});
test('before', function() {
var testBefore = function(beforeAmount, timesCalled) {
var beforeCalled = 0;
var before = _.before(beforeAmount, function() { beforeCalled++; });
while (timesCalled--) before();
return beforeCalled;
};
equal(testBefore(5, 5), 4, 'before(N) should not fire after being called N times');
equal(testBefore(5, 4), 4, 'before(N) should fire before being called N times');
equal(testBefore(0, 0), 0, 'before(0) should not fire immediately');
equal(testBefore(0, 1), 0, 'before(0) should not fire when first invoked');
var context = {num: 0};
var increment = _.before(3, function(){ return ++this.num; });
_.times(10, increment, context);
equal(increment(), 2, 'stores a memo to the last value');
equal(context.num, 2, 'provides context');
});
test('iteratee', function() {
var identity = _.iteratee();
equal(identity, _.identity, '_.iteratee is exposed as an external function.');
function fn() {
return arguments;
}
_.each([_.iteratee(fn), _.iteratee(fn, {})], function(cb) {
equal(cb().length, 0);
deepEqual(_.toArray(cb(1, 2, 3)), _.range(1, 4));
deepEqual(_.toArray(cb(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)), _.range(1, 11));
});
});
}());
});

File diff suppressed because it is too large Load Diff

View File

@@ -1,8 +1,8 @@
(function() {
var _ = typeof require == 'function' ? require('..') : window._;
$(document).ready(function() {
var templateSettings;
QUnit.module('Utility', {
module("Utility", {
setup: function() {
templateSettings = _.clone(_.templateSettings);
@@ -14,93 +14,50 @@
});
test('#750 - Return _ instance.', 2, function() {
test("#750 - Return _ instance.", 2, function() {
var instance = _([]);
ok(_(instance) === instance);
ok(new _(instance) === instance);
});
test('identity', function() {
var stooge = {name : 'moe'};
equal(_.identity(stooge), stooge, 'stooge is the same as his identity');
test("identity", function() {
var moe = {name : 'moe'};
equal(_.identity(moe), moe, 'moe is the same as his identity');
});
test('constant', function() {
var stooge = {name : 'moe'};
equal(_.constant(stooge)(), stooge, 'should create a function that returns stooge');
});
test('noop', function() {
strictEqual(_.noop('curly', 'larry', 'moe'), undefined, 'should always return undefined');
});
test('property', function() {
var stooge = {name : 'moe'};
equal(_.property('name')(stooge), 'moe', 'should return the property with the given name');
equal(_.property('name')(null), undefined, 'should return undefined for null values');
equal(_.property('name')(undefined), undefined, 'should return undefined for undefined values');
});
test('propertyOf', function() {
var stoogeRanks = _.propertyOf({curly: 2, moe: 1, larry: 3});
equal(stoogeRanks('curly'), 2, 'should return the property with the given name');
equal(stoogeRanks(null), undefined, 'should return undefined for null values');
equal(stoogeRanks(undefined), undefined, 'should return undefined for undefined values');
function MoreStooges() { this.shemp = 87; }
MoreStooges.prototype = {curly: 2, moe: 1, larry: 3};
var moreStoogeRanks = _.propertyOf(new MoreStooges());
equal(moreStoogeRanks('curly'), 2, 'should return properties from further up the prototype chain');
var nullPropertyOf = _.propertyOf(null);
equal(nullPropertyOf('curly'), undefined, 'should return undefined when obj is null');
var undefPropertyOf = _.propertyOf(undefined);
equal(undefPropertyOf('curly'), undefined, 'should return undefined when obj is undefined');
});
test('random', function() {
test("random", function() {
var array = _.range(1000);
var min = Math.pow(2, 31);
var max = Math.pow(2, 62);
ok(_.every(array, function() {
return _.random(min, max) >= min;
}), 'should produce a random number greater than or equal to the minimum number');
}), "should produce a random number greater than or equal to the minimum number");
ok(_.some(array, function() {
return _.random(Number.MAX_VALUE) > 0;
}), 'should produce a random number when passed `Number.MAX_VALUE`');
}), "should produce a random number when passed `Number.MAX_VALUE`");
});
test('now', function() {
var diff = _.now() - new Date().getTime();
ok(diff <= 0 && diff > -5, 'Produces the correct time in milliseconds');//within 5ms
});
test('uniqueId', function() {
test("uniqueId", function() {
var ids = [], i = 0;
while (i++ < 100) ids.push(_.uniqueId());
while(i++ < 100) ids.push(_.uniqueId());
equal(_.uniq(ids).length, ids.length, 'can generate a globally-unique stream of ids');
});
test('times', function() {
test("times", function() {
var vals = [];
_.times(3, function (i) { vals.push(i); });
deepEqual(vals, [0, 1, 2], 'is 0 indexed');
ok(_.isEqual(vals, [0,1,2]), "is 0 indexed");
//
vals = [];
_(3).times(function(i) { vals.push(i); });
deepEqual(vals, [0, 1, 2], 'works as a wrapper');
ok(_.isEqual(vals, [0,1,2]), "works as a wrapper");
// collects return values
deepEqual([0, 1, 2], _.times(3, function(i) { return i; }), 'collects return values');
deepEqual(_.times(0, _.identity), []);
deepEqual(_.times(-1, _.identity), []);
deepEqual(_.times(parseFloat('-Infinity'), _.identity), []);
ok(_.isEqual([0, 1, 2], _.times(3, function(i) { return i; })), "collects return values");
});
test('mixin', function() {
test("mixin", function() {
_.mixin({
myReverse: function(string) {
return string.split('').reverse().join('');
@@ -110,159 +67,124 @@
equal(_('champ').myReverse(), 'pmahc', 'mixed in a function to the OOP wrapper');
});
test('_.escape', function() {
test("_.escape", function() {
equal(_.escape("Curly & Moe"), "Curly &amp; Moe");
equal(_.escape("Curly &amp; Moe"), "Curly &amp;amp; Moe");
equal(_.escape(null), '');
});
test('_.unescape', function() {
var string = 'Curly & Moe';
test("_.unescape", function() {
var string = "Curly & Moe";
equal(_.unescape("Curly &amp; Moe"), string);
equal(_.unescape("Curly &amp;amp; Moe"), "Curly &amp; Moe");
equal(_.unescape(null), '');
equal(_.unescape(_.escape(string)), string);
equal(_.unescape(string), string, 'don\'t unescape unnecessarily');
});
// Don't care what they escape them to just that they're escaped and can be unescaped
test('_.escape & unescape', function() {
// test & (&amp;) seperately obviously
var escapeCharacters = ['<', '>', '"', '\'', '`'];
_.each(escapeCharacters, function(escapeChar) {
var str = 'a ' + escapeChar + ' string escaped';
var escaped = _.escape(str);
notEqual(str, escaped, escapeChar + ' is escaped');
equal(str, _.unescape(escaped), escapeChar + ' can be unescaped');
str = 'a ' + escapeChar + escapeChar + escapeChar + 'some more string' + escapeChar;
escaped = _.escape(str);
equal(escaped.indexOf(escapeChar), -1, 'can escape multiple occurances of ' + escapeChar);
equal(_.unescape(escaped), str, 'multiple occurrences of ' + escapeChar + ' can be unescaped');
});
// handles multiple escape characters at once
var joiner = ' other stuff ';
var allEscaped = escapeCharacters.join(joiner);
allEscaped += allEscaped;
ok(_.every(escapeCharacters, function(escapeChar) {
return allEscaped.indexOf(escapeChar) !== -1;
}), 'handles multiple characters');
ok(allEscaped.indexOf(joiner) >= 0, 'can escape multiple escape characters at the same time');
// test & -> &amp;
var str = 'some string & another string & yet another';
var escaped = _.escape(str);
ok(escaped.indexOf('&') !== -1, 'handles & aka &amp;');
equal(_.unescape(str), str, 'can unescape &amp;');
});
test('template', function() {
test("template", function() {
var basicTemplate = _.template("<%= thing %> is gettin' on my noives!");
var result = basicTemplate({thing : 'This'});
equal(result, "This is gettin' on my noives!", 'can do basic attribute interpolation');
var sansSemicolonTemplate = _.template('A <% this %> B');
equal(sansSemicolonTemplate(), 'A B');
var sansSemicolonTemplate = _.template("A <% this %> B");
equal(sansSemicolonTemplate(), "A B");
var backslashTemplate = _.template('<%= thing %> is \\ridanculous');
equal(backslashTemplate({thing: 'This'}), 'This is \\ridanculous');
var backslashTemplate = _.template("<%= thing %> is \\ridanculous");
equal(backslashTemplate({thing: 'This'}), "This is \\ridanculous");
var escapeTemplate = _.template('<%= a ? "checked=\\"checked\\"" : "" %>');
equal(escapeTemplate({a: true}), 'checked="checked"', 'can handle slash escapes in interpolations.');
var fancyTemplate = _.template('<ul><% ' +
' for (var key in people) { ' +
'%><li><%= people[key] %></li><% } %></ul>');
result = fancyTemplate({people : {moe : 'Moe', larry : 'Larry', curly : 'Curly'}});
equal(result, '<ul><li>Moe</li><li>Larry</li><li>Curly</li></ul>', 'can run arbitrary javascript in templates');
var fancyTemplate = _.template("<ul><% \
for (var key in people) { \
%><li><%= people[key] %></li><% } %></ul>");
result = fancyTemplate({people : {moe : "Moe", larry : "Larry", curly : "Curly"}});
equal(result, "<ul><li>Moe</li><li>Larry</li><li>Curly</li></ul>", 'can run arbitrary javascript in templates');
var escapedCharsInJavascriptTemplate = _.template('<ul><% _.each(numbers.split("\\n"), function(item) { %><li><%= item %></li><% }) %></ul>');
result = escapedCharsInJavascriptTemplate({numbers: 'one\ntwo\nthree\nfour'});
equal(result, '<ul><li>one</li><li>two</li><li>three</li><li>four</li></ul>', 'Can use escaped characters (e.g. \\n) in JavaScript');
var escapedCharsInJavascriptTemplate = _.template("<ul><% _.each(numbers.split('\\n'), function(item) { %><li><%= item %></li><% }) %></ul>");
result = escapedCharsInJavascriptTemplate({numbers: "one\ntwo\nthree\nfour"});
equal(result, "<ul><li>one</li><li>two</li><li>three</li><li>four</li></ul>", 'Can use escaped characters (e.g. \\n) in Javascript');
var namespaceCollisionTemplate = _.template('<%= pageCount %> <%= thumbnails[pageCount] %> <% _.each(thumbnails, function(p) { %><div class="thumbnail" rel="<%= p %>"></div><% }); %>');
var namespaceCollisionTemplate = _.template("<%= pageCount %> <%= thumbnails[pageCount] %> <% _.each(thumbnails, function(p) { %><div class=\"thumbnail\" rel=\"<%= p %>\"></div><% }); %>");
result = namespaceCollisionTemplate({
pageCount: 3,
thumbnails: {
1: 'p1-thumbnail.gif',
2: 'p2-thumbnail.gif',
3: 'p3-thumbnail.gif'
1: "p1-thumbnail.gif",
2: "p2-thumbnail.gif",
3: "p3-thumbnail.gif"
}
});
equal(result, '3 p3-thumbnail.gif <div class="thumbnail" rel="p1-thumbnail.gif"></div><div class="thumbnail" rel="p2-thumbnail.gif"></div><div class="thumbnail" rel="p3-thumbnail.gif"></div>');
equal(result, "3 p3-thumbnail.gif <div class=\"thumbnail\" rel=\"p1-thumbnail.gif\"></div><div class=\"thumbnail\" rel=\"p2-thumbnail.gif\"></div><div class=\"thumbnail\" rel=\"p3-thumbnail.gif\"></div>");
var noInterpolateTemplate = _.template('<div><p>Just some text. Hey, I know this is silly but it aids consistency.</p></div>');
var noInterpolateTemplate = _.template("<div><p>Just some text. Hey, I know this is silly but it aids consistency.</p></div>");
result = noInterpolateTemplate();
equal(result, '<div><p>Just some text. Hey, I know this is silly but it aids consistency.</p></div>');
equal(result, "<div><p>Just some text. Hey, I know this is silly but it aids consistency.</p></div>");
var quoteTemplate = _.template("It's its, not it's");
equal(quoteTemplate({}), "It's its, not it's");
var quoteInStatementAndBody = _.template('<% ' +
" if(foo == 'bar'){ " +
"%>Statement quotes and 'quotes'.<% } %>");
equal(quoteInStatementAndBody({foo: 'bar'}), "Statement quotes and 'quotes'.");
var quoteInStatementAndBody = _.template("<%\
if(foo == 'bar'){ \
%>Statement quotes and 'quotes'.<% } %>");
equal(quoteInStatementAndBody({foo: "bar"}), "Statement quotes and 'quotes'.");
var withNewlinesAndTabs = _.template('This\n\t\tis: <%= x %>.\n\tok.\nend.');
equal(withNewlinesAndTabs({x: 'that'}), 'This\n\t\tis: that.\n\tok.\nend.');
var template = _.template('<i><%- value %></i>');
result = template({value: '<script>'});
var template = _.template("<i><%- value %></i>");
var result = template({value: "<script>"});
equal(result, '<i>&lt;script&gt;</i>');
var stooge = {
name: 'Moe',
name: "Moe",
template: _.template("I'm <%= this.name %>")
};
equal(stooge.template(), "I'm Moe");
template = _.template('\n ' +
' <%\n ' +
' // a comment\n ' +
' if (data) { data += 12345; }; %>\n ' +
' <li><%= data %></li>\n '
);
equal(template({data : 12345}).replace(/\s/g, ''), '<li>24690</li>');
if (!$.browser.msie) {
var fromHTML = _.template($('#template').html());
equal(fromHTML({data : 12345}).replace(/\s/g, ''), '<li>24690</li>');
}
_.templateSettings = {
evaluate : /\{\{([\s\S]+?)\}\}/g,
interpolate : /\{\{=([\s\S]+?)\}\}/g
};
var custom = _.template('<ul>{{ for (var key in people) { }}<li>{{= people[key] }}</li>{{ } }}</ul>');
result = custom({people : {moe : 'Moe', larry : 'Larry', curly : 'Curly'}});
equal(result, '<ul><li>Moe</li><li>Larry</li><li>Curly</li></ul>', 'can run arbitrary javascript in templates');
var custom = _.template("<ul>{{ for (var key in people) { }}<li>{{= people[key] }}</li>{{ } }}</ul>");
result = custom({people : {moe : "Moe", larry : "Larry", curly : "Curly"}});
equal(result, "<ul><li>Moe</li><li>Larry</li><li>Curly</li></ul>", 'can run arbitrary javascript in templates');
var customQuote = _.template("It's its, not it's");
equal(customQuote({}), "It's its, not it's");
quoteInStatementAndBody = _.template("{{ if(foo == 'bar'){ }}Statement quotes and 'quotes'.{{ } }}");
equal(quoteInStatementAndBody({foo: 'bar'}), "Statement quotes and 'quotes'.");
var quoteInStatementAndBody = _.template("{{ if(foo == 'bar'){ }}Statement quotes and 'quotes'.{{ } }}");
equal(quoteInStatementAndBody({foo: "bar"}), "Statement quotes and 'quotes'.");
_.templateSettings = {
evaluate : /<\?([\s\S]+?)\?>/g,
interpolate : /<\?=([\s\S]+?)\?>/g
};
var customWithSpecialChars = _.template('<ul><? for (var key in people) { ?><li><?= people[key] ?></li><? } ?></ul>');
result = customWithSpecialChars({people : {moe : 'Moe', larry : 'Larry', curly : 'Curly'}});
equal(result, '<ul><li>Moe</li><li>Larry</li><li>Curly</li></ul>', 'can run arbitrary javascript in templates');
var customWithSpecialChars = _.template("<ul><? for (var key in people) { ?><li><?= people[key] ?></li><? } ?></ul>");
result = customWithSpecialChars({people : {moe : "Moe", larry : "Larry", curly : "Curly"}});
equal(result, "<ul><li>Moe</li><li>Larry</li><li>Curly</li></ul>", 'can run arbitrary javascript in templates');
var customWithSpecialCharsQuote = _.template("It's its, not it's");
equal(customWithSpecialCharsQuote({}), "It's its, not it's");
quoteInStatementAndBody = _.template("<? if(foo == 'bar'){ ?>Statement quotes and 'quotes'.<? } ?>");
equal(quoteInStatementAndBody({foo: 'bar'}), "Statement quotes and 'quotes'.");
var quoteInStatementAndBody = _.template("<? if(foo == 'bar'){ ?>Statement quotes and 'quotes'.<? } ?>");
equal(quoteInStatementAndBody({foo: "bar"}), "Statement quotes and 'quotes'.");
_.templateSettings = {
interpolate : /\{\{(.+?)\}\}/g
};
var mustache = _.template('Hello {{planet}}!');
equal(mustache({planet : 'World'}), 'Hello World!', 'can mimic mustache.js');
var mustache = _.template("Hello {{planet}}!");
equal(mustache({planet : "World"}), "Hello World!", "can mimic mustache.js");
var templateWithNull = _.template('a null undefined {{planet}}');
equal(templateWithNull({planet : 'world'}), 'a null undefined world', 'can handle missing escape and evaluate settings');
var templateWithNull = _.template("a null undefined {{planet}}");
equal(templateWithNull({planet : "world"}), "a null undefined world", "can handle missing escape and evaluate settings");
});
test('_.template provides the generated function source, when a SyntaxError occurs', function() {
@@ -285,49 +207,13 @@
strictEqual(_.result(obj, 'x'), 'x');
strictEqual(_.result(obj, 'y'), 'x');
strictEqual(_.result(obj, 'z'), undefined);
strictEqual(_.result(null, 'x'), undefined);
});
test('result returns a default value if object is null or undefined', function() {
strictEqual(_.result(null, 'b', 'default'), 'default');
strictEqual(_.result(undefined, 'c', 'default'), 'default');
strictEqual(_.result(''.match('missing'), 1, 'default'), 'default');
});
test('result returns a default value if property of object is missing', function() {
strictEqual(_.result({d: null}, 'd', 'default'), null);
strictEqual(_.result({e: false}, 'e', 'default'), false);
});
test('result only returns the default value if the object does not have the property or is undefined', function() {
strictEqual(_.result({}, 'b', 'default'), 'default');
strictEqual(_.result({d: undefined}, 'd', 'default'), 'default');
});
test('result does not return the default if the property of an object is found in the prototype', function() {
var Foo = function(){};
Foo.prototype.bar = 1;
strictEqual(_.result(new Foo, 'bar', 2), 1);
});
test('result does use the fallback when the result of invoking the property is undefined', function() {
var obj = {a: function() {}};
strictEqual(_.result(obj, 'a', 'failed'), undefined);
});
test('result fallback can use a function', function() {
var obj = {a: [1, 2, 3]};
strictEqual(_.result(obj, 'b', _.constant(5)), 5);
strictEqual(_.result(obj, 'b', function() {
return this.a;
}), obj.a, 'called with context');
strictEqual(_.result(null, 'x'), null);
});
test('_.templateSettings.variable', function() {
var s = '<%=data.x%>';
var data = {x: 'x'};
var tmp = _.template(s, {variable: 'data'});
strictEqual(tmp(data), 'x');
strictEqual(_.template(s, data, {variable: 'data'}), 'x');
_.templateSettings.variable = 'data';
strictEqual(_.template(s)(data), 'x');
});
@@ -348,22 +234,22 @@
strictEqual(templateEscaped({x: undefined}), '');
var templateWithProperty = _.template('<%=x.foo%>');
strictEqual(templateWithProperty({x: {}}), '');
strictEqual(templateWithProperty({x: {}}), '');
strictEqual(templateWithProperty({x: {} }), '');
strictEqual(templateWithProperty({x: {} }), '');
var templateWithPropertyEscaped = _.template('<%-x.foo%>');
strictEqual(templateWithPropertyEscaped({x: {}}), '');
strictEqual(templateWithPropertyEscaped({x: {}}), '');
strictEqual(templateWithPropertyEscaped({x: {} }), '');
strictEqual(templateWithPropertyEscaped({x: {} }), '');
});
test('interpolate evaluates code only once.', 2, function() {
var count = 0;
var template = _.template('<%= f() %>');
template({f: function(){ ok(!count++); }});
template({f: function(){ ok(!(count++)); }});
var countEscaped = 0;
var templateEscaped = _.template('<%- f() %>');
templateEscaped({f: function(){ ok(!countEscaped++); }});
templateEscaped({f: function(){ ok(!(countEscaped++)); }});
});
test('#746 - _.template settings are not modified.', 1, function() {
@@ -377,4 +263,4 @@
strictEqual(template(), '<<\nx\n>>');
});
}());
});

File diff suppressed because one or more lines are too long

Some files were not shown because too many files have changed in this diff Show More