mirror of
https://github.com/whoisclebs/lodash.git
synced 2026-01-29 06:27:49 +00:00
Compare commits
281 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
594002316c | ||
|
|
eccf92ebaf | ||
|
|
ad9ddc5621 | ||
|
|
1825dd916e | ||
|
|
dfcde8171e | ||
|
|
b0361183df | ||
|
|
71fe13b249 | ||
|
|
442f51224d | ||
|
|
974678f500 | ||
|
|
8329409c03 | ||
|
|
06c2ac2724 | ||
|
|
04e9e8f9d8 | ||
|
|
7a3330cb8c | ||
|
|
cae29941ea | ||
|
|
15cf2ad076 | ||
|
|
2f16f6dc23 | ||
|
|
528aebffe4 | ||
|
|
e82b2f0cbe | ||
|
|
73e64f3e4a | ||
|
|
15f5b1f830 | ||
|
|
1b0a77f9a8 | ||
|
|
0f82ae3644 | ||
|
|
de3b01b54b | ||
|
|
c17e3646d5 | ||
|
|
26aed3e89e | ||
|
|
74caea8f8f | ||
|
|
2cf07fa072 | ||
|
|
1181cd2fd7 | ||
|
|
850d55ab45 | ||
|
|
a0c91b8754 | ||
|
|
937bdc05c8 | ||
|
|
453755bfa1 | ||
|
|
400b6fbb61 | ||
|
|
8c4e882fa3 | ||
|
|
84eec23793 | ||
|
|
7dfe69f6a5 | ||
|
|
ada6115073 | ||
|
|
e1643566f9 | ||
|
|
053a9a6317 | ||
|
|
425b976cc0 | ||
|
|
5f5f1b1e09 | ||
|
|
e6f4935c7b | ||
|
|
6452e5976b | ||
|
|
2383dff317 | ||
|
|
de3e5042fb | ||
|
|
0dcc35152c | ||
|
|
8eecfcbfaf | ||
|
|
efa3e60f89 | ||
|
|
782df659bc | ||
|
|
0aa158824f | ||
|
|
da7fb44e5d | ||
|
|
4b59ef802e | ||
|
|
be5789cd56 | ||
|
|
9adf0e5d59 | ||
|
|
e2de22470e | ||
|
|
3b7ab2e553 | ||
|
|
8617dedc46 | ||
|
|
0b8f1a9a58 | ||
|
|
16748c0920 | ||
|
|
01ec585a44 | ||
|
|
b5f2295f37 | ||
|
|
d6ca0199b7 | ||
|
|
2257c5e547 | ||
|
|
b5a3d39799 | ||
|
|
a26c3e9d3c | ||
|
|
98a09532eb | ||
|
|
d736789bbc | ||
|
|
82a6cfc03a | ||
|
|
62e9c7c75a | ||
|
|
eb32bd45e7 | ||
|
|
4b95f07923 | ||
|
|
dea8ad4c49 | ||
|
|
96553b217c | ||
|
|
3f79ed5d91 | ||
|
|
1e4283aad3 | ||
|
|
1dda31a28c | ||
|
|
10c87012be | ||
|
|
bda00bf512 | ||
|
|
c8f871ff2a | ||
|
|
58dc0b1aef | ||
|
|
4cd4d8f31a | ||
|
|
b751fd738d | ||
|
|
f97c6fb94c | ||
|
|
219138ade6 | ||
|
|
9086d189b9 | ||
|
|
d1178defe0 | ||
|
|
691a561a95 | ||
|
|
aaaac93bd0 | ||
|
|
fd790566b2 | ||
|
|
db3b429784 | ||
|
|
40ed3278d4 | ||
|
|
d174b13111 | ||
|
|
1708663b32 | ||
|
|
6fdce4ad0d | ||
|
|
fff8d5f07d | ||
|
|
9c8e1f4706 | ||
|
|
0a1036c78f | ||
|
|
0e881a7972 | ||
|
|
839e52ba30 | ||
|
|
8f7d5dcb4d | ||
|
|
1104b28bc1 | ||
|
|
48521cb1e4 | ||
|
|
17e113dafb | ||
|
|
c33825a904 | ||
|
|
b07ef98c8f | ||
|
|
b3d68893df | ||
|
|
1329599987 | ||
|
|
2adf3f364c | ||
|
|
436ee34a02 | ||
|
|
4a6e17b214 | ||
|
|
6e9cbccde6 | ||
|
|
a0cb8ec124 | ||
|
|
21217dfda3 | ||
|
|
25ba18e570 | ||
|
|
a210377f35 | ||
|
|
07b9ca457f | ||
|
|
5f1372d39c | ||
|
|
01b84c79f0 | ||
|
|
4017443b1e | ||
|
|
fd2a17d244 | ||
|
|
126804f7c3 | ||
|
|
5167bbf59e | ||
|
|
8bcdfa2793 | ||
|
|
2f9cb6a91e | ||
|
|
662be14535 | ||
|
|
d6d065cd61 | ||
|
|
ac7f045708 | ||
|
|
ffe02ad7bf | ||
|
|
db1a87d10c | ||
|
|
4bae41ffd8 | ||
|
|
be36fb979f | ||
|
|
0f66d763e0 | ||
|
|
06f4743f51 | ||
|
|
9cc11b8774 | ||
|
|
de821e55ae | ||
|
|
463b5c6e49 | ||
|
|
65ab5fdb34 | ||
|
|
d2f7a035b3 | ||
|
|
bc0b924283 | ||
|
|
56ad6af5b2 | ||
|
|
c50bb3a5a9 | ||
|
|
d993a62263 | ||
|
|
82bc52b909 | ||
|
|
f31598f916 | ||
|
|
6a9efd8ac6 | ||
|
|
a9dddb6066 | ||
|
|
40cf5c99ef | ||
|
|
42f58cbbb3 | ||
|
|
fd9c780015 | ||
|
|
383b92b207 | ||
|
|
7036ed5e2f | ||
|
|
30666aa111 | ||
|
|
9614d68baa | ||
|
|
c25fb4c743 | ||
|
|
09d5222b1f | ||
|
|
426ca78bf7 | ||
|
|
a77a0945fe | ||
|
|
5311a0f903 | ||
|
|
d421656be8 | ||
|
|
04459eaa50 | ||
|
|
3beda8eea0 | ||
|
|
5e894be06b | ||
|
|
bc8f93b596 | ||
|
|
2fb93bac99 | ||
|
|
d0c94c1aef | ||
|
|
77242bfb95 | ||
|
|
5d2d86bffc | ||
|
|
8492c13e72 | ||
|
|
e4eb5dadda | ||
|
|
8532dc4b75 | ||
|
|
1ca26ce676 | ||
|
|
d8e3e823a7 | ||
|
|
473dd7660b | ||
|
|
5afeed56ef | ||
|
|
b91b04f652 | ||
|
|
25de44a23d | ||
|
|
00cfb95971 | ||
|
|
f4ba0e1191 | ||
|
|
6499643769 | ||
|
|
f85287a444 | ||
|
|
483bc9ad87 | ||
|
|
93b89a93c1 | ||
|
|
10064c046c | ||
|
|
a5aecb9d0e | ||
|
|
de1e889f1d | ||
|
|
16f89b40c3 | ||
|
|
0e387d2cda | ||
|
|
837c15e4f9 | ||
|
|
ae7e353169 | ||
|
|
6c1bbd2344 | ||
|
|
27247e8e56 | ||
|
|
08249d78ea | ||
|
|
827091e522 | ||
|
|
13d901bf8d | ||
|
|
e69bdabc99 | ||
|
|
e8d19265e4 | ||
|
|
49e3a49dc5 | ||
|
|
82a7c01898 | ||
|
|
c0d7dbf639 | ||
|
|
569caa0bf2 | ||
|
|
f88ea1ee7d | ||
|
|
d5a8fa0b97 | ||
|
|
3f8f96edea | ||
|
|
04fb4aff28 | ||
|
|
83c6fb089e | ||
|
|
9d8d17b964 | ||
|
|
39d4842ff5 | ||
|
|
cad8473986 | ||
|
|
5f085ccb52 | ||
|
|
b406246689 | ||
|
|
cbe46afdff | ||
|
|
a59d6dc3c7 | ||
|
|
2afb2dd5fd | ||
|
|
4fc3c969d3 | ||
|
|
1796ce324b | ||
|
|
5e04c7f827 | ||
|
|
20fcede440 | ||
|
|
012c1833f2 | ||
|
|
32e8e03256 | ||
|
|
dca653cb92 | ||
|
|
0805eca979 | ||
|
|
17935a78ff | ||
|
|
e16918ee32 | ||
|
|
78471b4595 | ||
|
|
c30bcdd515 | ||
|
|
ac78c5f4e5 | ||
|
|
57a990ce25 | ||
|
|
24825b42a2 | ||
|
|
4f7323f7fc | ||
|
|
a228be85e2 | ||
|
|
fa565bdbdf | ||
|
|
2dc53223e5 | ||
|
|
958ac72805 | ||
|
|
f7297b84e7 | ||
|
|
9a7d9e7bb8 | ||
|
|
fa9df75cf7 | ||
|
|
e3ec76418b | ||
|
|
102d6d8c84 | ||
|
|
a742b5f3e2 | ||
|
|
a2a3bb291f | ||
|
|
b7c0ac7d67 | ||
|
|
13b1fc6b44 | ||
|
|
3939fcf6e7 | ||
|
|
13abbb81af | ||
|
|
019f0153c8 | ||
|
|
8abc2925e0 | ||
|
|
996c9a032a | ||
|
|
22d3794d22 | ||
|
|
ba948a38e9 | ||
|
|
e8a522c4df | ||
|
|
c60f3da32e | ||
|
|
0c92d3cbb2 | ||
|
|
e4fc8dd6fe | ||
|
|
1a849e2de0 | ||
|
|
ffdd79f86b | ||
|
|
e87e46b1b6 | ||
|
|
3ca81a4ff7 | ||
|
|
5477d3c292 | ||
|
|
08300183b3 | ||
|
|
095c77f22c | ||
|
|
09926e63a3 | ||
|
|
87d70f29a1 | ||
|
|
3a7661b111 | ||
|
|
ec976953cd | ||
|
|
1837562b50 | ||
|
|
f3bec4fc37 | ||
|
|
c2117ef4fd | ||
|
|
910804ecd1 | ||
|
|
ce5ae1dfdd | ||
|
|
2c31411ffb | ||
|
|
84d69fa2a1 | ||
|
|
2aea296d19 | ||
|
|
2b0bffc362 | ||
|
|
83356142c1 | ||
|
|
24dcc6947c | ||
|
|
a7e3136a0b | ||
|
|
71639cfea7 | ||
|
|
8c2d39fb82 | ||
|
|
e060d29337 | ||
|
|
79e9156d2f | ||
|
|
9100db55b0 |
5
.gitignore
vendored
5
.gitignore
vendored
@@ -1,4 +1,5 @@
|
||||
*.custom.*
|
||||
.DS_Store
|
||||
dist/
|
||||
*.custom.*
|
||||
node_modules/
|
||||
vendor/closure-compiler/
|
||||
vendor/uglifyjs/
|
||||
|
||||
11
.jamignore
11
.jamignore
@@ -1,7 +1,10 @@
|
||||
*.custom.*
|
||||
.*
|
||||
dist/
|
||||
*.custom.*
|
||||
build.js
|
||||
index.js
|
||||
build/
|
||||
doc/*.php
|
||||
node_modules/
|
||||
perf/*.sh
|
||||
test/*.sh
|
||||
perf/
|
||||
test/
|
||||
vendor/
|
||||
|
||||
12
.npmignore
12
.npmignore
@@ -1,16 +1,22 @@
|
||||
*.custom.*
|
||||
.*
|
||||
dist/
|
||||
*.custom.*
|
||||
*.d.ts
|
||||
doc/*.php
|
||||
node_modules/
|
||||
perf/*.html
|
||||
perf/*-ui.js
|
||||
perf/*.sh
|
||||
test/*.html
|
||||
test/*-ui.js
|
||||
test/*.sh
|
||||
vendor/*.gz
|
||||
vendor/backbone/
|
||||
vendor/docdown/
|
||||
vendor/benchmark.js/*.jar
|
||||
vendor/closure-compiler
|
||||
vendor/docdown
|
||||
vendor/firebug-lite/
|
||||
vendor/jquery/
|
||||
vendor/qunit/qunit/*.css
|
||||
vendor/requirejs/
|
||||
vendor/uglifyjs
|
||||
vendor/underscore/test/
|
||||
|
||||
7
.travis.yml
Normal file
7
.travis.yml
Normal file
@@ -0,0 +1,7 @@
|
||||
language: node_js
|
||||
node_js:
|
||||
- 0.6
|
||||
- 0.8
|
||||
before_script:
|
||||
- "curl -H 'Accept: application/vnd.github.v3.raw' https://api.github.com/repos/bestiejs/lodash/git/blobs/aa29a2ecf6f51d4da5a2a418c0d4ea0e368ee80d | tar xvz -C vendor"
|
||||
- "curl -H 'Accept: application/vnd.github.v3.raw' https://api.github.com/repos/bestiejs/lodash/git/blobs/9869c4443fb22598235d1019fcc8245be41e8889 | tar xvz -C vendor"
|
||||
236
README.md
236
README.md
@@ -1,15 +1,17 @@
|
||||
# Lo-Dash <sup>v0.6.1</sup>
|
||||
# Lo-Dash <sup>v0.9.0</sup>
|
||||
[](http://travis-ci.org/bestiejs/lodash)
|
||||
|
||||
A drop-in replacement<sup>[*](https://github.com/bestiejs/lodash/wiki/Drop-in-Disclaimer)</sup> for Underscore.js, from the devs behind [jsPerf.com](http://jsperf.com), delivering [performance](http://lodash.com/benchmarks), [bug fixes](https://github.com/bestiejs/lodash#resolved-underscorejs-issues-30), and [additional features](https://github.com/bestiejs/lodash#features).
|
||||
A drop-in replacement<sup>[*](https://github.com/bestiejs/lodash/wiki/Drop-in-Disclaimer)</sup> for Underscore.js, from the devs behind [jsPerf.com](http://jsperf.com), delivering [performance](http://lodash.com/benchmarks), [bug fixes](https://github.com/bestiejs/lodash#resolved-underscorejs-issues), and [additional features](http://lodash.com/#features).
|
||||
|
||||
Lo-Dash’s performance is gained by avoiding slower native methods, instead opting for simplified non-ES5 compliant methods optimized for common usage, and by leveraging function compilation to reduce the number of overall function calls.
|
||||
|
||||
## Download
|
||||
|
||||
* [Development source](https://raw.github.com/bestiejs/lodash/v0.6.1/lodash.js)
|
||||
* [Production source](https://raw.github.com/bestiejs/lodash/v0.6.1/lodash.min.js)
|
||||
* CDN copies of ≤ [v0.6.1](http://cdnjs.cloudflare.com/ajax/libs/lodash.js/0.6.1/lodash.min.js) are available on [cdnjs](http://cdnjs.com/) thanks to [CloudFlare](http://www.cloudflare.com/)
|
||||
* For optimal performance, [create a custom build](https://github.com/bestiejs/lodash#custom-builds) with only the features you need
|
||||
* [Development build](https://raw.github.com/bestiejs/lodash/v0.9.0/lodash.js)
|
||||
* [Production build](https://raw.github.com/bestiejs/lodash/v0.9.0/lodash.min.js)
|
||||
* [Underscore build](https://raw.github.com/bestiejs/lodash/v0.9.0/lodash.underscore.min.js) tailored for projects already using Underscore
|
||||
* CDN copies of ≤ [v0.9.0](http://cdnjs.cloudflare.com/ajax/libs/lodash.js/0.9.0/lodash.min.js) are available on [cdnjs](http://cdnjs.com/) thanks to [CloudFlare](http://www.cloudflare.com/)
|
||||
* For optimal file size, [create a custom build](https://github.com/bestiejs/lodash#custom-builds) with only the features you need
|
||||
|
||||
## Dive in
|
||||
|
||||
@@ -27,41 +29,34 @@ For more information check out these screencasts over Lo-Dash:
|
||||
* [Lo-Dash optimizations and custom builds](https://vimeo.com/44154601)
|
||||
* [Lo-Dash’s origin and why it’s a better utility belt](https://vimeo.com/44154600)
|
||||
* [Unit testing in Lo-Dash](https://vimeo.com/45865290)
|
||||
* [Lo-Dash’s approach to native method use](https://vimeo.com/48576012)
|
||||
|
||||
## Features
|
||||
|
||||
* AMD loader support ([RequireJS](http://requirejs.org/), [curl.js](https://github.com/cujojs/curl), etc.)
|
||||
* [_.bind](http://lodash.com/docs#bind) supports *“lazy”* binding
|
||||
* [_.clone](http://lodash.com/docs#clone) supports *“deep”* cloning
|
||||
* [_.countBy](http://lodash.com/docs#countBy) as a companion function for [_.groupBy](http://lodash.com/docs#groupBy) and [_.sortBy](http://lodash.com/docs#sortBy)
|
||||
* [_.debounce](http://lodash.com/docs#debounce)’ed functions match [_.throttle](http://lodash.com/docs#throttle)’ed functions’ return value behavior
|
||||
* [_.drop](http://lodash.com/docs#drop) for the inverse functionality of [_.pick](http://lodash.com/docs#pick)
|
||||
* [_.forEach](http://lodash.com/docs#forEach) is chainable and supports exiting iteration early
|
||||
* [_.forIn](http://lodash.com/docs#forIn) for iterating over an object’s own and inherited properties
|
||||
* [_.forOwn](http://lodash.com/docs#forOwn) for iterating over an object’s own properties
|
||||
* [_.groupBy](http://lodash.com/docs#groupBy), [_.sortedIndex](http://lodash.com/docs#sortedIndex), and [_.uniq](http://lodash.com/docs#uniq) accept a `thisArg` argument
|
||||
* [_.indexOf](http://lodash.com/docs#indexOf) and [_.lastIndexOf](http://lodash.com/docs#lastIndexOf) accept a `fromIndex` argument
|
||||
* [_.isPlainObject](http://lodash.com/docs#isPlainObject) checks if values are created by the `Object` constructor
|
||||
* [_.lateBind](http://lodash.com/docs#lateBind) for late binding
|
||||
* [_.merge](http://lodash.com/docs#merge) for a *“deep”* [_.extend](http://lodash.com/docs#extend)
|
||||
* [_.partial](http://lodash.com/docs#partial) for partial application without `this` binding
|
||||
* [_.pick](http://lodash.com/docs#pick) and [_.drop](http://lodash.com/docs#drop) accept `callback` and `thisArg` arguments
|
||||
* [_.sortBy](http://lodash.com/docs#sortBy) performs a [stable](http://en.wikipedia.org/wiki/Sorting_algorithm#Stability) sort
|
||||
* [_.pick](http://lodash.com/docs#pick) and [_.omit](http://lodash.com/docs#omit) accept `callback` and `thisArg` arguments
|
||||
* [_.template](http://lodash.com/docs#template) utilizes [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) for easier debugging
|
||||
* [_.unescape](http://lodash.com/docs#unescape) to unescape strings escaped by [_.escape](http://lodash.com/docs#escape)
|
||||
* [_.where](http://lodash.com/docs#where) for filtering collections by contained properties
|
||||
* [_.zipObject](http://lodash.com/docs#zipObject) for composing objects
|
||||
* [_.contains](http://lodash.com/docs#contains), [_.size](http://lodash.com/docs#size), [_.toArray](http://lodash.com/docs#toArray),
|
||||
[and more…](http://lodash.com/docs "_.every, _.filter, _.find, _.forEach, _.groupBy, _.invoke, _.map, _.pluck, _.reduce, _.reduceRight, _.reject, _.some, _sortBy") accept strings
|
||||
[and more…](http://lodash.com/docs "_.countBy, _.every, _.filter, _.find, _.forEach, _.groupBy, _.invoke, _.map, _.pluck, _.reduce, _.reduceRight, _.reject, _.some, _.sortBy, _.where") accept strings
|
||||
|
||||
## Support
|
||||
|
||||
Lo-Dash has been tested in at least Chrome 5-21, Firefox 1-15, IE 6-9, Opera 9.25-12, Safari 3-6, Node.js 0.4.8-0.8.8, Narwhal 0.3.2, RingoJS 0.8, and Rhino 1.7RC5.
|
||||
Lo-Dash has been tested in at least Chrome 5~22, Firefox 1~16, IE 6-10, Opera 9.25-12, Safari 3-6, Node.js 0.4.8-0.8.12, Narwhal 0.3.2, RingoJS 0.8, and Rhino 1.7RC5.
|
||||
|
||||
## Custom builds
|
||||
|
||||
Custom builds make it easy to create lightweight versions of Lo-Dash containing only the methods you need.
|
||||
We handle all the method dependency and alias mapping for you.
|
||||
To top it off, we handle all method dependency and alias mapping for you.
|
||||
|
||||
* Backbone builds, containing all methods required by Backbone, may be created using the `backbone` modifier argument.
|
||||
* Backbone builds, with only methods required by Backbone, may be created using the `backbone` modifier argument.
|
||||
```bash
|
||||
lodash backbone
|
||||
```
|
||||
@@ -86,42 +81,74 @@ lodash mobile
|
||||
lodash strict
|
||||
```
|
||||
|
||||
* Underscore builds, containing only methods included in Underscore, may be created using the `underscore` modifier argument.
|
||||
* Underscore builds, tailored for projects already using Underscore, may be created using the `underscore` modifier argument.
|
||||
```bash
|
||||
lodash underscore
|
||||
```
|
||||
|
||||
Custom builds may be created in three ways:
|
||||
Custom builds may be created using the following commands:
|
||||
|
||||
1. Use the `category` argument to pass the categories of methods to include in the build.<br>
|
||||
Valid categories are *“arrays”*, *“chaining”*, *“collections”*, *“functions”*, *“objects”*, and *“utilities”*.
|
||||
* Use the `category` argument to pass comma separated categories of methods to include in the build.<br>
|
||||
Valid categories (case-insensitive) are *“arrays”*, *“chaining”*, *“collections”*, *“functions”*, *“objects”*, and *“utilities”*.
|
||||
```bash
|
||||
lodash category=collections,functions
|
||||
lodash category="collections, functions"
|
||||
```
|
||||
|
||||
2. Use the `exclude` argument to pass the names of methods to exclude from the build.
|
||||
* Use the `exports` argument to pass comma separated names of ways to export the `LoDash` function.<br>
|
||||
Valid exports are *“amd”*, *“commonjs”*, *“global”*, *“node”*, and *“none”*.
|
||||
```bash
|
||||
lodash exclude=union,uniq,zip
|
||||
lodash exclude="union, uniq, zip"
|
||||
lodash exports=amd,commonjs,node
|
||||
lodash exports="amd, commonjs, node"
|
||||
```
|
||||
|
||||
3. Use the `include` argument to pass the names of methods to include in the build.
|
||||
* Use the `iife` argument to specify code to replace the immediately-invoked function expression that wraps Lo-Dash.
|
||||
```bash
|
||||
lodash iife="!function(window,undefined){%output%}(this)"
|
||||
```
|
||||
|
||||
* Use the `include` argument to pass comma separated method/category names to include in the build.
|
||||
```bash
|
||||
lodash include=each,filter,map
|
||||
lodash include="each, filter, map"
|
||||
```
|
||||
|
||||
All arguments, except `backbone` with `underscore`, `exclude` with `include`, and `legacy` with `csp`/`mobile`, may be combined.
|
||||
|
||||
* Use the `minus` argument to pass comma separated method/category names to remove from those included in the build.
|
||||
```bash
|
||||
lodash backbone legacy category=utilities exclude=first,last
|
||||
lodash underscore mobile strict category=functions include=pick,uniq
|
||||
lodash underscore minus=result,shuffle
|
||||
lodash underscore minus="result, shuffle"
|
||||
```
|
||||
|
||||
The `lodash` command-line utility is available when Lo-Dash is installed as a global package (i.e. `npm install -g lodash`).
|
||||
* Use the `plus` argument to pass comma separated method/category names to add to those included in the build.
|
||||
```bash
|
||||
lodash backbone plus=random,template
|
||||
lodash backbone plus="random, template"
|
||||
```
|
||||
|
||||
Custom builds are saved to `lodash.custom.js` and `lodash.custom.min.js`.
|
||||
* Use the `template` argument to pass the file path pattern used to match template files to precompile
|
||||
```bash
|
||||
lodash template="./*.jst"
|
||||
```
|
||||
|
||||
* Use the `settings` argument to pass the template settings used when precompiling templates
|
||||
```bash
|
||||
lodash settings="{interpolate:/\\{\\{([\\s\\S]+?)\\}\\}/g}"
|
||||
```
|
||||
|
||||
All arguments, except `legacy` with `csp` or `mobile`, may be combined.<br>
|
||||
Unless specified by `-o` or `--output`, all files created are saved to the current working directory.
|
||||
|
||||
The following options are also supported:
|
||||
|
||||
* `-c`, `--stdout` Write output to standard output
|
||||
* `-d`, `--debug` Write only the debug output
|
||||
* `-h`, `--help` Display help information
|
||||
* `-m`, `--minify` Write only the minified output
|
||||
* `-o`, `--output` Write output to a given path/filename
|
||||
* `-s`, `--silent` Skip status updates normally logged to the console
|
||||
* `-V`, `--version` Output current version of Lo-Dash
|
||||
|
||||
The `lodash` command-line utility is available when Lo-Dash is installed as a global package (i.e. `npm install -g lodash`).
|
||||
|
||||
## Installation and usage
|
||||
|
||||
@@ -135,7 +162,9 @@ Using [npm](http://npmjs.org/):
|
||||
|
||||
```bash
|
||||
npm install lodash
|
||||
|
||||
npm install -g lodash
|
||||
npm link lodash
|
||||
```
|
||||
|
||||
In [Node.js](http://nodejs.org/) and [RingoJS v0.8.0+](http://ringojs.org/):
|
||||
@@ -144,6 +173,8 @@ In [Node.js](http://nodejs.org/) and [RingoJS v0.8.0+](http://ringojs.org/):
|
||||
var _ = require('lodash');
|
||||
```
|
||||
|
||||
**Note:** If Lo-Dash is installed globally, [run `npm link lodash`](http://blog.nodejs.org/2011/03/23/npm-1-0-global-vs-local-installation/) in your project’s root directory before requiring it.
|
||||
|
||||
In [RingoJS v0.7.0-](http://ringojs.org/):
|
||||
|
||||
```js
|
||||
@@ -169,119 +200,38 @@ require({
|
||||
});
|
||||
```
|
||||
|
||||
## Resolved Underscore.js issues <sup>(30+)</sup>
|
||||
## Resolved Underscore.js issues
|
||||
|
||||
* Allow iteration of objects with a `length` property [[#148](https://github.com/documentcloud/underscore/issues/148), [#154](https://github.com/documentcloud/underscore/issues/154), [#252](https://github.com/documentcloud/underscore/issues/252), [#448](https://github.com/documentcloud/underscore/issues/448), [#659](https://github.com/documentcloud/underscore/issues/659), [test](https://github.com/bestiejs/lodash/blob/v0.6.1/test/test.js#L578-584)]
|
||||
* Ensure array-like objects with invalid `length` properties are treated like regular objects [[test](https://github.com/bestiejs/lodash/blob/v0.6.1/test/test.js#L526-536)]
|
||||
* Ensure *“Arrays”*, “Collections”, and “Objects” methods don’t error when passed falsey arguments [[#650](https://github.com/documentcloud/underscore/pull/650), [test](https://github.com/bestiejs/lodash/blob/v0.6.1/test/test.js#L1668-1703)]
|
||||
* Ensure *“Collections”* methods allow string `collection` arguments [[#247](https://github.com/documentcloud/underscore/issues/247), [#276](https://github.com/documentcloud/underscore/issues/276), [#561](https://github.com/documentcloud/underscore/pull/561), [test](https://github.com/bestiejs/lodash/blob/v0.6.1/test/test.js#L538-555)]
|
||||
* Ensure templates compiled with errors are inspectable [[#666](https://github.com/documentcloud/underscore/issues/666), [test](https://github.com/bestiejs/lodash/blob/v0.6.1/test/test.js#L1383-1386)]
|
||||
* Fix cross-browser object iteration bugs [[#60](https://github.com/documentcloud/underscore/issues/60), [#376](https://github.com/documentcloud/underscore/issues/376), [test](https://github.com/bestiejs/lodash/blob/v0.6.1/test/test.js#L589-614)]
|
||||
* Handle arrays with `undefined` values correctly in IE < 9 [[#601](https://github.com/documentcloud/underscore/issues/601)]
|
||||
* Methods should work on pages with incorrectly shimmed native methods [[#7](https://github.com/documentcloud/underscore/issues/7), [test](https://github.com/bestiejs/lodash/blob/v0.6.1/test/test.js#L117-123)]
|
||||
* Register as an AMD module, but still export to global [[#431](https://github.com/documentcloud/underscore/pull/431), [test](https://github.com/bestiejs/lodash/blob/v0.6.1/test/test.js#L101-115)]
|
||||
* `_(…)` should return passed wrapper instances [[test](https://github.com/bestiejs/lodash/blob/v0.6.1/test/test.js#L135-138)]
|
||||
* `_.clone` should allow `deep` cloning [[#595](https://github.com/documentcloud/underscore/pull/595), [test](https://github.com/bestiejs/lodash/blob/v0.6.1/test/test.js#L205-220)]
|
||||
* `_.contains` should work with strings [[#667](https://github.com/documentcloud/underscore/pull/667), [test](https://github.com/bestiejs/lodash/blob/v0.6.1/test/test.js#L275-284)]
|
||||
* `_.countBy` and `_.groupBy` should only add values to own, not inherited, properties [[test](https://github.com/bestiejs/lodash/blob/v0.6.1/test/test.js#L292-299)]
|
||||
* `_.escape` should return an empty string when passed `null` or `undefined` [[#427](https://github.com/documentcloud/underscore/issues/427), [test](https://github.com/bestiejs/lodash/blob/v0.6.1/test/test.js#L402-405)]
|
||||
* `_.extend` should recursively extend objects [[#379](https://github.com/documentcloud/underscore/pull/379), [#718](https://github.com/documentcloud/underscore/issues/718), [test](https://github.com/bestiejs/lodash/blob/v0.6.1/test/test.js#L979-1001)]
|
||||
* `_.forEach` should be chainable [[#142](https://github.com/documentcloud/underscore/issues/142), [test](https://github.com/bestiejs/lodash/blob/v0.6.1/test/test.js#L521-524)]
|
||||
* `_.forEach` should allow exiting iteration early [[#211](https://github.com/documentcloud/underscore/issues/211), [test](https://github.com/bestiejs/lodash/blob/v0.6.1/test/test.js#L616-635)]
|
||||
* `_.isElement` should use strict equality for its duck type check [[test](https://github.com/bestiejs/lodash/blob/v0.6.1/test/test.js#L731-740)]
|
||||
* `_.isEmpty` and `_.size` should support jQuery/MooTools DOM query collections [[#690](https://github.com/documentcloud/underscore/pull/690), [test](https://github.com/bestiejs/lodash/blob/v0.6.1/test/test.js#L767-772)]
|
||||
* `_.isEqual` should return `true` for like-objects from different documents [[test](https://github.com/bestiejs/lodash/blob/v0.6.1/test/test.js#L808-828)]
|
||||
* `_.isObject` should avoid V8 bug [#2291](http://code.google.com/p/v8/issues/detail?id=2291) [[#605](https://github.com/documentcloud/underscore/issues/605), [test](https://github.com/bestiejs/lodash/blob/v0.6.1/test/test.js#L836-848)]
|
||||
* `_.isNaN(new Number(NaN))` should return `true` [[test](https://github.com/bestiejs/lodash/blob/v0.6.1/test/test.js#L856-858)]
|
||||
* `_.keys` and `_.size` should work with `arguments` objects cross-browser [[#396](https://github.com/documentcloud/underscore/issues/396), [#653](https://github.com/documentcloud/underscore/issues/653), [test](https://github.com/bestiejs/lodash/blob/v0.6.1/test/test.js#L912-914)]
|
||||
* `_.once` should free the given function for garbage collection [[#693](https://github.com/documentcloud/underscore/pull/693)]
|
||||
* `_.range` should coerce arguments to numbers [[#634](https://github.com/documentcloud/underscore/issues/634), [#683](https://github.com/documentcloud/underscore/issues/683), [test](https://github.com/bestiejs/lodash/blob/v0.6.1/test/test.js#L1170-1173)]
|
||||
* `_.reduceRight` should pass correct callback arguments when iterating objects [[test](https://github.com/bestiejs/lodash/blob/v0.6.1/test/test.js#L1205-1219)]
|
||||
* `_.size` should return the `length` of string values [[test](https://github.com/bestiejs/lodash/blob/v0.6.1/test/test.js#L1263-1265)]
|
||||
* `_.sortedIndex` should support arrays with high `length` values [[test](https://github.com/bestiejs/lodash/blob/v0.6.1/test/test.js#L1353-1362)]
|
||||
* `_.template` should not augment the `options` object [[test](https://github.com/bestiejs/lodash/blob/v0.6.1/test/test.js#L1377-1381)]
|
||||
* `_.throttle` should work when called in a loop [[#502](https://github.com/documentcloud/underscore/issues/502), [test](https://github.com/bestiejs/lodash/blob/v0.6.1/test/test.js#L1473-1483)]
|
||||
* `_.toArray` uses custom `toArray` methods of arrays and strings [[test](https://github.com/bestiejs/lodash/blob/v0.6.1/test/test.js#L1510-1518)]
|
||||
* `_.zipObject` should accept less than two arguments [[test](https://github.com/bestiejs/lodash/blob/v0.6.1/test/test.js#L1630-1632)]
|
||||
|
||||
## Optimized methods <sup>(50+)</sup>
|
||||
|
||||
* `_.bind`
|
||||
* `_.bindAll`
|
||||
* `_.clone`
|
||||
* `_.compact`
|
||||
* `_.contains`, `_.include`
|
||||
* `_.defaults`
|
||||
* `_.defer`
|
||||
* `_.difference`
|
||||
* `_.drop`, `_.omit`
|
||||
* `_.each`
|
||||
* `_.escape`
|
||||
* `_.every`, `_.all`
|
||||
* `_.extend`
|
||||
* `_.filter`, `_.select`
|
||||
* `_.find`, `_.detect`
|
||||
* `_.flatten`
|
||||
* `_.forEach`, `_.each`
|
||||
* `_.functions`, `_.methods`
|
||||
* `_.groupBy`
|
||||
* `_.indexOf`
|
||||
* `_.intersection`
|
||||
* `_.invoke`
|
||||
* `_.isArguments`
|
||||
* `_.isDate`
|
||||
* `_.isEmpty`
|
||||
* `_.isFinite`
|
||||
* `_.isFunction`
|
||||
* `_.isObject`
|
||||
* `_.isNumber`
|
||||
* `_.isRegExp`
|
||||
* `_.isString`
|
||||
* `_.keys`
|
||||
* `_.lastIndexOf`
|
||||
* `_.map`, `_.collect`
|
||||
* `_.max`
|
||||
* `_.memoize`
|
||||
* `_.min`
|
||||
* `_.mixin`
|
||||
* `_.pick`
|
||||
* `_.pluck`
|
||||
* `_.reduce`, `_.foldl`, `_.inject`
|
||||
* `_.reject`
|
||||
* `_.result`
|
||||
* `_.shuffle`
|
||||
* `_.some`, `_.any`
|
||||
* `_.sortBy`
|
||||
* `_.sortedIndex`
|
||||
* `_.template`
|
||||
* `_.throttle`
|
||||
* `_.times`
|
||||
* `_.toArray`
|
||||
* `_.union`
|
||||
* `_.uniq`, `_.unique`
|
||||
* `_.values`
|
||||
* `_.without`
|
||||
* `_.wrap`
|
||||
* `_.zip`
|
||||
* plus all `_(…)` method wrappers
|
||||
* Add AMD loader support [[#431](https://github.com/documentcloud/underscore/pull/431), [test](https://github.com/bestiejs/lodash/blob/v0.9.0/test/test.js#L116-138)]
|
||||
* Allow iteration of objects with a `length` property [[#799](https://github.com/documentcloud/underscore/pull/799), [test](https://github.com/bestiejs/lodash/blob/v0.9.0/test/test.js#L508-514)]
|
||||
* Ensure *“Collections”* methods allow string `collection` arguments [[#247](https://github.com/documentcloud/underscore/issues/247), [#276](https://github.com/documentcloud/underscore/issues/276), [#561](https://github.com/documentcloud/underscore/pull/561), [test](https://github.com/bestiejs/lodash/blob/v0.9.0/test/test.js#L468-485)]
|
||||
* Fix cross-browser object iteration bugs [[#60](https://github.com/documentcloud/underscore/issues/60), [#376](https://github.com/documentcloud/underscore/issues/376), [test](https://github.com/bestiejs/lodash/blob/v0.9.0/test/test.js#L521-545)]
|
||||
* Methods should work on pages with incorrectly shimmed native methods [[#7](https://github.com/documentcloud/underscore/issues/7), [#742](https://github.com/documentcloud/underscore/issues/742), [test](https://github.com/bestiejs/lodash/blob/v0.9.0/test/test.js#L140-146)]
|
||||
* `_.clone` should allow `deep` cloning [[#595](https://github.com/documentcloud/underscore/pull/595), [test](https://github.com/bestiejs/lodash/blob/v0.9.0/test/test.js#L212-223)]
|
||||
* `_.contains` should work with strings [[#667](https://github.com/documentcloud/underscore/pull/667), [test](https://github.com/bestiejs/lodash/blob/v0.9.0/test/test.js#L265-274)]
|
||||
* `_.extend` should recursively extend objects [[#379](https://github.com/documentcloud/underscore/pull/379), [#718](https://github.com/documentcloud/underscore/issues/718), [test](https://github.com/bestiejs/lodash/blob/v0.9.0/test/test.js#L989-1011)]
|
||||
* `_.forEach` should be chainable [[#142](https://github.com/documentcloud/underscore/issues/142), [test](https://github.com/bestiejs/lodash/blob/v0.9.0/test/test.js#L463-466)]
|
||||
* `_.forEach` should allow exiting iteration early [[#211](https://github.com/documentcloud/underscore/issues/211), [test](https://github.com/bestiejs/lodash/blob/v0.9.0/test/test.js#L551-569)]
|
||||
* `_.isEmpty` should support jQuery/MooTools DOM query collections [[#690](https://github.com/documentcloud/underscore/pull/690), [test](https://github.com/bestiejs/lodash/blob/v0.9.0/test/test.js#L710-715)]
|
||||
* `_.isObject` should avoid V8 bug [#2291](http://code.google.com/p/v8/issues/detail?id=2291) [[#605](https://github.com/documentcloud/underscore/issues/605), [test](https://github.com/bestiejs/lodash/blob/v0.9.0/test/test.js#L770-782)]
|
||||
* `_.keys` should work with `arguments` objects cross-browser [[#396](https://github.com/documentcloud/underscore/issues/396), [test](https://github.com/bestiejs/lodash/blob/v0.9.0/test/test.js#L863-865)]
|
||||
* `_.range` should coerce arguments to numbers [[#634](https://github.com/documentcloud/underscore/issues/634), [#683](https://github.com/documentcloud/underscore/issues/683), [test](https://github.com/bestiejs/lodash/blob/v0.9.0/test/test.js#L1264-1267)]
|
||||
|
||||
## Release Notes
|
||||
|
||||
### <sup>v0.6.1</sup>
|
||||
### <sup>v0.9.0</sup>
|
||||
|
||||
* Ensured IE conditional compilation isn’t enabled by the `useSourceURL` test
|
||||
* Optimized `isPlainObject`
|
||||
|
||||
### <sup>v0.6.0</sup>
|
||||
|
||||
* Added `callback` and `thisArg` arguments to `_.drop` and `_.pick`
|
||||
* Added `hasObjectSpliceBug` test to avoid `delete` operator use
|
||||
* Added `_.omit` alias for `_.drop`
|
||||
* Added [_.unescape](http://lodash.com/docs#unescape)
|
||||
* Ensured `_.reduce` works with string objects in IE < 9
|
||||
* Made compiled methods take advantage of engines with strict mode optimizations
|
||||
* Optimized `_.intersection` and removed its dependency on `_.every`
|
||||
* Reduced the file size of the `underscore` build
|
||||
* Added a `sourceURL` option to `_.template`
|
||||
* Ensured `_.where` returns an empty array if passed an empty `properties` object
|
||||
* Expanded `_.isFinite` to return `true` for numeric strings
|
||||
* Reduced `_.intersection`, `_.omit`, `_.pick`, `_.sortedIndex`, and `_.where`
|
||||
* Reduced the `npm` package file size by only downloading the minifiers for global installs
|
||||
* Reduced Lo-Dash's file size
|
||||
* Removed compilation from `_.bindAll`, `_.contains`, `_.countBy`, `_.every`,
|
||||
`_.filter`, `_.find`, `_.functions`, `_.groupBy`, `_.invert`, `_.invoke`,
|
||||
`_.isEmpty`, `_.map`, `_.merge`, `_.omit`, `_.pairs`, `_.pick`, `_.pluck`,
|
||||
`_.reduce`, `_.reject`, `_.some`, `_.sortBy`, `_.values`, `_.where`, and
|
||||
internal `shimKeys`
|
||||
|
||||
The full changelog is available [here](https://github.com/bestiejs/lodash/wiki/Changelog).
|
||||
|
||||
|
||||
187
build/minify.js
187
build/minify.js
@@ -8,24 +8,20 @@
|
||||
path = require('path'),
|
||||
spawn = require('child_process').spawn;
|
||||
|
||||
/** The directory that is the base of the repository */
|
||||
var basePath = path.join(__dirname, '../');
|
||||
/** The path of the directory that is the base of the repository */
|
||||
var basePath = fs.realpathSync(path.join(__dirname, '..'));
|
||||
|
||||
/** The directory where the Closure Compiler is located */
|
||||
/** The path of the directory where the Closure Compiler is located */
|
||||
var closurePath = path.join(basePath, 'vendor', 'closure-compiler', 'compiler.jar');
|
||||
|
||||
/** The distribution directory */
|
||||
var distPath = path.join(basePath, 'dist');
|
||||
|
||||
/** Load other modules */
|
||||
var preprocess = require(path.join(__dirname, 'pre-compile')),
|
||||
postprocess = require(path.join(__dirname, 'post-compile')),
|
||||
uglifyJS = require(path.join(basePath, 'vendor', 'uglifyjs', 'uglify-js'));
|
||||
var preprocess = require('./pre-compile'),
|
||||
postprocess = require('./post-compile'),
|
||||
uglifyJS = require('../vendor/uglifyjs/uglify-js');
|
||||
|
||||
/** Closure Compiler command-line options */
|
||||
/** The Closure Compiler command-line options */
|
||||
var closureOptions = [
|
||||
'--compilation_level=ADVANCED_OPTIMIZATIONS',
|
||||
'--language_in=ECMASCRIPT5_STRICT',
|
||||
'--warning_level=QUIET'
|
||||
];
|
||||
|
||||
@@ -35,15 +31,52 @@
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
/**
|
||||
* The exposed `minify` function minifies a given Lo-Dash `source` and invokes
|
||||
* the `onComplete` callback when finished.
|
||||
* Minifies a given Lo-Dash `source` and invokes the `options.onComplete`
|
||||
* callback when finished. The `onComplete` callback is invoked with one
|
||||
* argument; (outputSource).
|
||||
*
|
||||
* @param {String} source The source to minify.
|
||||
* @param {String} workingName The name to give temporary files creates during the minification process.
|
||||
* @param {Function} onComplete A function called when minification has completed.
|
||||
* @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, workingName, onComplete) {
|
||||
new Minify(source, workingName, onComplete);
|
||||
function minify(source, options) {
|
||||
source || (source = '');
|
||||
options || (options = {});
|
||||
|
||||
// juggle arguments
|
||||
if (Array.isArray(source)) {
|
||||
// convert commands to an options object
|
||||
options = source;
|
||||
|
||||
var filePath = options[options.length - 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');
|
||||
|
||||
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 = {
|
||||
'isSilent': isSilent,
|
||||
'isTemplate': isTemplate,
|
||||
'outputPath': outputPath
|
||||
};
|
||||
|
||||
source = fs.readFileSync(filePath, 'utf8');
|
||||
}
|
||||
new Minify(source, options);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -52,24 +85,31 @@
|
||||
* @private
|
||||
* @constructor
|
||||
* @param {String} source The source to minify.
|
||||
* @param {String} workingName The name to give temporary files creates during the minification process.
|
||||
* @param {Function} onComplete A function called when minification has completed.
|
||||
* @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, workingName, onComplete) {
|
||||
// create the destination directory if it doesn't exist
|
||||
if (!fs.existsSync(distPath)) {
|
||||
// avoid errors when called as a npm executable
|
||||
try {
|
||||
fs.mkdirSync(distPath);
|
||||
} catch(e) { }
|
||||
function Minify(source, options) {
|
||||
// juggle arguments
|
||||
if (typeof source == 'object' && source) {
|
||||
options = source || options;
|
||||
source = options.source || '';
|
||||
}
|
||||
|
||||
this.compiled = {};
|
||||
this.hybrid = {};
|
||||
this.uglified = {};
|
||||
this.onComplete = onComplete;
|
||||
this.source = source = preprocess(source);
|
||||
this.workingName = workingName;
|
||||
this.isSilent = !!options.isSilent;
|
||||
this.isTemplate = !!options.isTemplate;
|
||||
this.outputPath = options.outputPath;
|
||||
|
||||
source = preprocess(source, options);
|
||||
this.source = source;
|
||||
|
||||
this.onComplete = options.onComplete || function(source) {
|
||||
fs.writeFileSync(this.outputPath, source, 'utf8');
|
||||
};
|
||||
|
||||
// begin the minification process
|
||||
closureCompile.call(this, source, onClosureCompile.bind(this));
|
||||
@@ -84,25 +124,33 @@
|
||||
* @private
|
||||
* @param {String} source The JavaScript source to minify.
|
||||
* @param {String} [message] The message to log.
|
||||
* @param {Function} callback The function to call once the process completes.
|
||||
* @param {Function} callback The function called once the process has completed.
|
||||
*/
|
||||
function closureCompile(source, message, callback) {
|
||||
// the standard error stream, standard output stream, and Closure Compiler process
|
||||
var options = closureOptions.slice();
|
||||
|
||||
// use simple optimizations when minifying template files
|
||||
if (this.isTemplate) {
|
||||
options = options.map(function(value) {
|
||||
return value.replace(/^(--compilation_level)=.+$/, '$1=SIMPLE_OPTIMIZATIONS');
|
||||
});
|
||||
}
|
||||
// the standard error stream, standard output stream, and the Closure Compiler process
|
||||
var error = '',
|
||||
output = '',
|
||||
compiler = spawn('java', ['-jar', closurePath].concat(closureOptions));
|
||||
compiler = spawn('java', ['-jar', closurePath].concat(options));
|
||||
|
||||
// juggle arguments
|
||||
if (typeof message == 'function') {
|
||||
callback = message;
|
||||
message = null;
|
||||
}
|
||||
|
||||
console.log(message == null
|
||||
? 'Compressing ' + this.workingName + ' using the Closure Compiler...'
|
||||
: message
|
||||
);
|
||||
|
||||
if (!this.isSilent) {
|
||||
console.log(message == null
|
||||
? 'Compressing ' + path.basename(this.outputPath, '.js') + ' using the Closure Compiler...'
|
||||
: message
|
||||
);
|
||||
}
|
||||
compiler.stdout.on('data', function(data) {
|
||||
// append the data to the output stream
|
||||
output += data;
|
||||
@@ -136,7 +184,7 @@
|
||||
* @private
|
||||
* @param {String} source The JavaScript source to minify.
|
||||
* @param {String} [message] The message to log.
|
||||
* @param {Function} callback The function to call once the process completes.
|
||||
* @param {Function} callback The function called once the process has completed.
|
||||
*/
|
||||
function uglify(source, message, callback) {
|
||||
var exception,
|
||||
@@ -148,12 +196,12 @@
|
||||
callback = message;
|
||||
message = null;
|
||||
}
|
||||
|
||||
console.log(message == null
|
||||
? 'Compressing ' + this.workingName + ' using UglifyJS...'
|
||||
: message
|
||||
);
|
||||
|
||||
if (!this.isSilent) {
|
||||
console.log(message == null
|
||||
? 'Compressing ' + path.basename(this.outputPath, '.js') + ' using UglifyJS...'
|
||||
: message
|
||||
);
|
||||
}
|
||||
try {
|
||||
result = ugly.gen_code(
|
||||
// enable unsafe transformations
|
||||
@@ -203,9 +251,11 @@
|
||||
if (exception) {
|
||||
throw exception;
|
||||
}
|
||||
if (!this.isSilent) {
|
||||
console.log('Done. Size: %d bytes.', result.length);
|
||||
}
|
||||
// store the gzipped result and report the size
|
||||
this.compiled.gzip = result;
|
||||
console.log('Done. Size: %d bytes.', result.length);
|
||||
|
||||
// next, minify the source using only UglifyJS
|
||||
uglify.call(this, this.source, onUglify.bind(this));
|
||||
@@ -238,11 +288,13 @@
|
||||
if (exception) {
|
||||
throw exception;
|
||||
}
|
||||
var message = 'Compressing ' + this.workingName + ' using hybrid minification...';
|
||||
if (!this.isSilent) {
|
||||
console.log('Done. Size: %d bytes.', result.length);
|
||||
}
|
||||
var message = 'Compressing ' + path.basename(this.outputPath, '.js') + ' using hybrid minification...';
|
||||
|
||||
// store the gzipped result and report the size
|
||||
this.uglified.gzip = result;
|
||||
console.log('Done. Size: %d bytes.', result.length);
|
||||
|
||||
// next, minify the Closure Compiler minified source using UglifyJS
|
||||
uglify.call(this, this.compiled.source, message, onHybrid.bind(this));
|
||||
@@ -275,9 +327,11 @@
|
||||
if (exception) {
|
||||
throw exception;
|
||||
}
|
||||
if (!this.isSilent) {
|
||||
console.log('Done. Size: %d bytes.', result.length);
|
||||
}
|
||||
// store the gzipped result and report the size
|
||||
this.hybrid.gzip = result;
|
||||
console.log('Done. Size: %d bytes.', result.length);
|
||||
|
||||
// finish by choosing the smallest compressed file
|
||||
onComplete.call(this);
|
||||
@@ -291,26 +345,10 @@
|
||||
function onComplete() {
|
||||
var compiled = this.compiled,
|
||||
hybrid = this.hybrid,
|
||||
name = this.workingName,
|
||||
uglified = this.uglified;
|
||||
|
||||
// avoid errors when called as a npm executable
|
||||
try {
|
||||
// save the Closure Compiled version to disk
|
||||
fs.writeFileSync(path.join(distPath, name + '.compiler.js'), compiled.source);
|
||||
fs.writeFileSync(path.join(distPath, name + '.compiler.js.gz'), compiled.gzip);
|
||||
|
||||
// save the Uglified version to disk
|
||||
fs.writeFileSync(path.join(distPath, name + '.uglify.js'), uglified.source);
|
||||
fs.writeFileSync(path.join(distPath, name + '.uglify.js.gz'), uglified.gzip);
|
||||
|
||||
// save the hybrid minified version to disk
|
||||
fs.writeFileSync(path.join(distPath, name + '.hybrid.js'), hybrid.source);
|
||||
fs.writeFileSync(path.join(distPath, name + '.hybrid.js.gz'), hybrid.gzip);
|
||||
} catch(e) { }
|
||||
|
||||
// select the smallest gzipped file and use its minified counterpart as the
|
||||
// official minified release (ties go to Closure Compiler)
|
||||
// official minified release (ties go to the Closure Compiler)
|
||||
var min = Math.min(compiled.gzip.length, hybrid.gzip.length, uglified.gzip.length);
|
||||
|
||||
// pass the minified source to the minify instances "onComplete" callback
|
||||
@@ -334,14 +372,11 @@
|
||||
// was invoked directly (e.g. `node minify.js source.js`) and write to
|
||||
// `<filename>.min.js`
|
||||
(function() {
|
||||
var filePath = process.argv[2],
|
||||
dirPath = path.dirname(filePath),
|
||||
source = fs.readFileSync(filePath, 'utf8'),
|
||||
workingName = path.basename(filePath, '.js') + '.min';
|
||||
|
||||
minify(source, workingName, function(result) {
|
||||
fs.writeFileSync(path.join(dirPath, workingName + '.js'), result, 'utf8');
|
||||
});
|
||||
var options = process.argv;
|
||||
if (options.length < 3) {
|
||||
return;
|
||||
}
|
||||
minify(options);
|
||||
}());
|
||||
}
|
||||
}());
|
||||
|
||||
@@ -6,11 +6,15 @@
|
||||
var fs = require('fs');
|
||||
|
||||
/** The minimal license/copyright template */
|
||||
var licenseTemplate =
|
||||
'/*!\n' +
|
||||
' Lo-Dash @VERSION lodash.com/license\n' +
|
||||
' Underscore.js 1.3.3 github.com/documentcloud/underscore/blob/master/LICENSE\n' +
|
||||
'*/';
|
||||
var licenseTemplate = {
|
||||
'lodash':
|
||||
'/*!\n' +
|
||||
' Lo-Dash @VERSION lodash.com/license\n' +
|
||||
' Underscore.js 1.4.2 underscorejs.org/LICENSE\n' +
|
||||
'*/',
|
||||
'underscore':
|
||||
'/*! Underscore.js @VERSION underscorejs.org/LICENSE */'
|
||||
};
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
@@ -22,29 +26,37 @@
|
||||
* @returns {String} Returns the processed source.
|
||||
*/
|
||||
function postprocess(source) {
|
||||
// exit early if snippet isn't found
|
||||
var snippet = /VERSION\s*[=:]\s*([\'"])(.*?)\1/.exec(source);
|
||||
if (!snippet) {
|
||||
return source;
|
||||
}
|
||||
// move vars exposed by the Closure Compiler into the IIFE
|
||||
source = source.replace(/^((?:(['"])use strict\2;)?(?:var (?:[a-z]+=(?:!0|!1|null)[,;])+)?)([\s\S]*?function[^)]+\){)/, '$3$1');
|
||||
|
||||
// set the version
|
||||
var license = licenseTemplate.replace('@VERSION', snippet[2]);
|
||||
|
||||
// move vars exposed by Closure Compiler into the IIFE
|
||||
source = source.replace(/^([^(\n]+)\s*(\(function[^)]+\){)/, '$2$1');
|
||||
// avoid bugs with the Closure Compiler
|
||||
source = source
|
||||
// correct overly aggressive Closure Compiler minification
|
||||
.replace(/prototype\s*=\s*{\s*valueOf\s*:\s*1\s*}/, 'prototype={valueOf:1,y:1}')
|
||||
// restore `arrayRef` and `objectRef` values modified by pre-compile.js
|
||||
.replace(/= *Array.prototype/, '=[]')
|
||||
.replace(/= *Object.prototype/, '={}');
|
||||
|
||||
// unescape properties (i.e. foo["bar"] => foo.bar)
|
||||
source = source.replace(/(\w)\["([^."]+)"\]/g, '$1.$2');
|
||||
source = source.replace(/(\w)\["([^."]+)"\]/g, function(match, left, right) {
|
||||
return /\W/.test(right) ? match : (left + '.' + right);
|
||||
});
|
||||
|
||||
// correct AMD module definition for AMD build optimizers
|
||||
source = source.replace(/("function")\s*==\s*(typeof define)\s*&&\s*\(?\s*("object")\s*==\s*(typeof define\.amd)\s*&&\s*(define\.amd)\s*\)?/, '$2==$1&&$4==$3&&$5');
|
||||
|
||||
// add license
|
||||
source = license + '\n;' + source;
|
||||
|
||||
// add trailing semicolon
|
||||
return source.replace(/[\s;]*$/, ';');
|
||||
if (source) {
|
||||
source = source.replace(/[\s;]*$/, ';');
|
||||
}
|
||||
// exit early if version snippet isn't found
|
||||
var snippet = /VERSION\s*[=:]\s*([\'"])(.*?)\1/.exec(source);
|
||||
if (!snippet) {
|
||||
return source;
|
||||
}
|
||||
// add license
|
||||
return licenseTemplate[/call\(this\);?$/.test(source) ? 'underscore' : 'lodash']
|
||||
.replace('@VERSION', snippet[2]) + '\n;' + source;
|
||||
}
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
@@ -52,13 +64,20 @@
|
||||
// expose `postprocess`
|
||||
if (module != require.main) {
|
||||
module.exports = postprocess;
|
||||
} else {
|
||||
}
|
||||
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 source = fs.readFileSync(process.argv[2], 'utf8');
|
||||
fs.writeFileSync(process.argv[2], postprocess(source), 'utf8');
|
||||
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');
|
||||
}());
|
||||
}
|
||||
}());
|
||||
|
||||
106
build/post-install.js
Normal file
106
build/post-install.js
Normal file
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env node
|
||||
;(function () {
|
||||
'use strict';
|
||||
|
||||
/** Load Node modules */
|
||||
var exec = require('child_process').exec,
|
||||
fs = require('fs'),
|
||||
https = require('https'),
|
||||
path = require('path'),
|
||||
tar = require('tar'),
|
||||
zlib = require('zlib');
|
||||
|
||||
/** 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 Git object ID of `closure-compiler.tar.gz` */
|
||||
var closureId = 'aa29a2ecf6f51d4da5a2a418c0d4ea0e368ee80d';
|
||||
|
||||
/** The Git object ID of `uglifyjs.tar.gz` */
|
||||
var uglifyId = '9869c4443fb22598235d1019fcc8245be41e8889';
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
/**
|
||||
* 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, invoked with one argument (exception),
|
||||
* 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 onComplete = options.onComplete,
|
||||
title = options.title;
|
||||
|
||||
function callback(exception) {
|
||||
if (exception) {
|
||||
console.error('There was a problem downloading ' + title + '.');
|
||||
}
|
||||
onComplete(exception);
|
||||
}
|
||||
|
||||
console.log('Downloading ' + title + '...');
|
||||
|
||||
https.get({
|
||||
'host': 'api.github.com',
|
||||
'path': '/repos/bestiejs/lodash/git/blobs/' + options.id,
|
||||
'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.
|
||||
'Accept': 'application/vnd.github.v3.raw'
|
||||
}
|
||||
}, function(response) {
|
||||
var parser = new tar.Extract({
|
||||
'path': options.path
|
||||
})
|
||||
.on('end', callback)
|
||||
.on('error', callback);
|
||||
|
||||
response.pipe(zlib.createUnzip()).pipe(parser);
|
||||
})
|
||||
.on('error', callback);
|
||||
}
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
exec('npm -g root', function(exception, stdout, stderr) {
|
||||
if (exception || stderr) {
|
||||
console.error('There was a problem loading the npm registry.');
|
||||
process.exit(1);
|
||||
}
|
||||
// exit early if not a global install
|
||||
if (path.resolve(basePath, '..') != stdout.trim()) {
|
||||
return;
|
||||
}
|
||||
// download the Closure Compiler
|
||||
getDependency({
|
||||
'title': 'the Closure Compiler',
|
||||
'id': closureId,
|
||||
'path': vendorPath,
|
||||
'onComplete':function(exceptionA) {
|
||||
// download UglifyJS
|
||||
getDependency({
|
||||
'title': 'UglifyJS',
|
||||
'id': uglifyId,
|
||||
'path': vendorPath,
|
||||
'onComplete': function(exceptionB) {
|
||||
process.exit(exceptionA || exceptionB ? 1 : 0);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
}());
|
||||
@@ -11,82 +11,36 @@
|
||||
'argsLength',
|
||||
'callback',
|
||||
'collection',
|
||||
'concat',
|
||||
'createCallback',
|
||||
'ctor',
|
||||
'hasOwnProperty',
|
||||
'identity',
|
||||
'index',
|
||||
'isArguments',
|
||||
'iteratee',
|
||||
'iteratorBind',
|
||||
'length',
|
||||
'nativeKeys',
|
||||
'object',
|
||||
'objectTypes',
|
||||
'ownIndex',
|
||||
'ownProps',
|
||||
'prop',
|
||||
'propertyIsEnumerable',
|
||||
'propIndex',
|
||||
'props',
|
||||
'result',
|
||||
'skipProto',
|
||||
'slice',
|
||||
'stringClass',
|
||||
'thisArg',
|
||||
'toString',
|
||||
'value',
|
||||
|
||||
// lesser used variables
|
||||
'accumulator',
|
||||
'args',
|
||||
'arrayLikeClasses',
|
||||
'ArrayProto',
|
||||
'bind',
|
||||
'callee',
|
||||
'className',
|
||||
'compareAscending',
|
||||
'destValue',
|
||||
'forIn',
|
||||
'found',
|
||||
'funcs',
|
||||
'indexOf',
|
||||
'indicator',
|
||||
'isArguments',
|
||||
'isArr',
|
||||
'isArray',
|
||||
'isFunc',
|
||||
'isFunction',
|
||||
'isPlainObject',
|
||||
'methodName',
|
||||
'noaccum',
|
||||
'objectClass',
|
||||
'objectTypes',
|
||||
'pass',
|
||||
'properties',
|
||||
'property',
|
||||
'propsLength',
|
||||
'recursive',
|
||||
'source',
|
||||
'stack',
|
||||
'stackLength',
|
||||
'target',
|
||||
'valueProp'
|
||||
'value'
|
||||
];
|
||||
|
||||
/** Used to minify `compileIterator` option properties */
|
||||
var iteratorOptions = [
|
||||
'args',
|
||||
'array',
|
||||
'arrayBranch',
|
||||
'beforeLoop',
|
||||
'arrayLoop',
|
||||
'bottom',
|
||||
'exit',
|
||||
'firstArg',
|
||||
'hasDontEnumBug',
|
||||
'inLoop',
|
||||
'init',
|
||||
'isKeysFast',
|
||||
'object',
|
||||
'objectBranch',
|
||||
'objectLoop',
|
||||
'noArgsEnum',
|
||||
'noCharByIndex',
|
||||
'shadowed',
|
||||
@@ -104,9 +58,8 @@
|
||||
/** Used to protect the specified properties from getting minified */
|
||||
var propWhitelist = [
|
||||
'_',
|
||||
'_chain',
|
||||
'_wrapped',
|
||||
'__proto__',
|
||||
'__chain__',
|
||||
'__wrapped__',
|
||||
'after',
|
||||
'all',
|
||||
'amd',
|
||||
@@ -115,7 +68,6 @@
|
||||
'bind',
|
||||
'bindAll',
|
||||
'chain',
|
||||
'clearTimeout',
|
||||
'clone',
|
||||
'collect',
|
||||
'compact',
|
||||
@@ -135,6 +87,7 @@
|
||||
'escape',
|
||||
'evaluate',
|
||||
'every',
|
||||
'exports',
|
||||
'extend',
|
||||
'filter',
|
||||
'find',
|
||||
@@ -146,6 +99,7 @@
|
||||
'forIn',
|
||||
'forOwn',
|
||||
'functions',
|
||||
'global',
|
||||
'groupBy',
|
||||
'has',
|
||||
'head',
|
||||
@@ -157,6 +111,7 @@
|
||||
'inject',
|
||||
'interpolate',
|
||||
'intersection',
|
||||
'invert',
|
||||
'invoke',
|
||||
'isArguments',
|
||||
'isArray',
|
||||
@@ -173,12 +128,14 @@
|
||||
'isNull',
|
||||
'isNumber',
|
||||
'isObject',
|
||||
'isPlainObject',
|
||||
'isRegExp',
|
||||
'isString',
|
||||
'isUndefined',
|
||||
'keys',
|
||||
'last',
|
||||
'lastIndexOf',
|
||||
'lateBind',
|
||||
'map',
|
||||
'max',
|
||||
'memoize',
|
||||
@@ -187,12 +144,15 @@
|
||||
'min',
|
||||
'mixin',
|
||||
'noConflict',
|
||||
'object',
|
||||
'omit',
|
||||
'once',
|
||||
'opera',
|
||||
'pairs',
|
||||
'partial',
|
||||
'pick',
|
||||
'pluck',
|
||||
'random',
|
||||
'range',
|
||||
'reduce',
|
||||
'reduceRight',
|
||||
@@ -200,7 +160,6 @@
|
||||
'rest',
|
||||
'result',
|
||||
'select',
|
||||
'setTimeout',
|
||||
'shuffle',
|
||||
'size',
|
||||
'some',
|
||||
@@ -228,7 +187,10 @@
|
||||
'without',
|
||||
'wrap',
|
||||
'zip',
|
||||
'zipObject'
|
||||
|
||||
// properties used by underscore.js
|
||||
'_chain',
|
||||
'_wrapped'
|
||||
];
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
@@ -236,39 +198,39 @@
|
||||
/**
|
||||
* Pre-process a given Lo-Dash `source`, preparing it for minification.
|
||||
*
|
||||
* @param {String} source The source to process.
|
||||
* @param {String} [source=''] The source to process.
|
||||
* @param {Object} [options={}] The options object.
|
||||
* @returns {String} Returns the processed source.
|
||||
*/
|
||||
function preprocess(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;
|
||||
}
|
||||
|
||||
// remove copyright to add later in post-compile.js
|
||||
source = source.replace(/\/\*![\s\S]+?\*\//, '');
|
||||
|
||||
// remove unrecognized JSDoc tags so Closure Compiler won't complain
|
||||
source = source.replace(/@(?:alias|category)\b.*/g, '');
|
||||
// replace `arrayRef` and `objectRef` values to avoid a bug in the Closure Compiler
|
||||
source = source
|
||||
.replace(/(arrayRef *= *)\[\]/, '$1Array.prototype')
|
||||
.replace(/(objectRef *= *)\{\}/, '$1Object.prototype');
|
||||
|
||||
// manually convert `arrayLikeClasses` property assignments because
|
||||
// Closure Compiler errors trying to minify them
|
||||
source = source.replace(/(arrayLikeClasses =)[\s\S]+?= *true/,
|
||||
"$1{'[object Arguments]': true, '[object Array]': true, '[object Boolean]': false, " +
|
||||
"'[object Date]': false, '[object Function]': false, '[object Number]': false, " +
|
||||
"'[object Object]': false, '[object RegExp]': false, '[object String]': true }"
|
||||
);
|
||||
|
||||
// manually convert `cloneableClasses` property assignments because
|
||||
// Closure Compiler errors trying to minify them
|
||||
source = source.replace(/(cloneableClasses =)[\s\S]+?= *true/,
|
||||
"$1{'[object Arguments]': false, '[object Array]': true, '[object Boolean]': true, " +
|
||||
"'[object Date]': true, '[object Function]': false, '[object Number]': true, " +
|
||||
"'[object Object]': true, '[object RegExp]': true, '[object String]': true }"
|
||||
);
|
||||
|
||||
// add brackets to whitelisted properties so Closure Compiler won't mung them
|
||||
// add brackets to whitelisted properties so the Closure Compiler won't mung them
|
||||
// http://code.google.com/closure/compiler/docs/api-tutorial3.html#export
|
||||
source = source.replace(RegExp('\\.(' + propWhitelist.join('|') + ')\\b', 'g'), "['$1']");
|
||||
|
||||
// remove brackets from `_.escape()` in `_.template`
|
||||
source = source.replace(/__e *= *_\['escape']/g, '__e=_.escape');
|
||||
|
||||
// remove brackets from `_.escape()` in underscore.js `_.template`
|
||||
source = source.replace(/_\['escape'\]\(__t'/g, '_.escape(__t');
|
||||
|
||||
// remove brackets from `collection.indexOf` in `_.contains`
|
||||
source = source.replace("collection['indexOf'](target)", 'collection.indexOf(target)');
|
||||
|
||||
@@ -278,13 +240,16 @@
|
||||
// remove whitespace from string literals
|
||||
source = source.replace(/'(?:(?=(\\?))\1.)*?'/g, function(string) {
|
||||
// avoids removing the '\n' of the `stringEscapes` object
|
||||
return string.replace(/\[object |delete |else if|function | in |return\s+[\w']|throw |typeof |use strict|var |@ |'\\n'|\\\\n|\\n|\s+/g, function(match) {
|
||||
return string.replace(/\[object |delete |else |function | in |return\s+[\w']|throw |typeof |use strict|var |@ |'\\n'|\\\\n|\\n|\s+/g, function(match) {
|
||||
return match == false || match == '\\n' ? '' : match;
|
||||
});
|
||||
});
|
||||
|
||||
// add newline to `+"__p+='"` in underscore.js `_.template`
|
||||
source = source.replace(/\+"__p\+='"/g, '+"\\n__p+=\'"');
|
||||
|
||||
// remove whitespace from `_.template` related regexes
|
||||
source = source.replace(/(?:reDelimiterCode\w+|reEmptyString\w+|reInsertVariable) *=.+/g, function(match) {
|
||||
source = source.replace(/(?:reEmptyString\w+|reInsertVariable) *=.+/g, function(match) {
|
||||
return match.replace(/ |\\n/g, '');
|
||||
});
|
||||
|
||||
@@ -300,54 +265,29 @@
|
||||
source = source.replace(/(?:\n +\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/)?\n *try *\{(?:\s*\/\/.*)*\n *var useSourceURL[\s\S]+?catch[^}]+}\n/, '');
|
||||
|
||||
// remove debug sourceURL use in `_.template`
|
||||
source = source.replace(/(?:\s*\/\/.*\n)* *if *\(useSourceURL[^}]+}/, '');
|
||||
source = source.replace(/(?:\s*\/\/.*\n)* *var sourceURL[^;]+;|\+ *sourceURL/g, '');
|
||||
|
||||
// minify internal properties used by 'compareAscending', `_.clone`, `_.merge`, and `_.sortBy`
|
||||
// minify internal properties used by 'compareAscending' and `_.sortBy`
|
||||
(function() {
|
||||
var properties = ['criteria', 'index', 'source', 'value'],
|
||||
snippets = source.match(/( +)(?:function clone|function compareAscending|var merge|var sortBy)\b[\s\S]+?\n\1}/g);
|
||||
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,
|
||||
isCompilable = /(?:var merge|var sortBy)\b/.test(modified),
|
||||
isInlined = !/\bcreateIterator\b/.test(modified);
|
||||
var modified = snippet;
|
||||
|
||||
// minify properties
|
||||
properties.forEach(function(property, index) {
|
||||
var reBracketProp = RegExp("\\['(" + property + ")'\\]", 'g'),
|
||||
reDotProp = RegExp('\\.' + property + '\\b', 'g'),
|
||||
rePropColon = RegExp("(')?\\b" + property + "\\1 *:", 'g');
|
||||
rePropColon = RegExp("([^?\\s])\\s*([\"'])?\\b" + property + "\\2 *:", 'g');
|
||||
|
||||
if (isCompilable) {
|
||||
// add quotes around properties in the inlined `_.merge` and `_.sortBy`
|
||||
// of the mobile build so Closure Compiler won't mung them
|
||||
if (isInlined) {
|
||||
modified = modified
|
||||
.replace(reBracketProp, "['" + minNames[index] + "']")
|
||||
.replace(reDotProp, "['" + minNames[index] + "']")
|
||||
.replace(rePropColon, "'" + minNames[index] + "':");
|
||||
}
|
||||
else {
|
||||
modified = modified
|
||||
.replace(reBracketProp, '.' + minNames[index])
|
||||
.replace(reDotProp, '.' + minNames[index])
|
||||
.replace(rePropColon, minNames[index] + ':');
|
||||
}
|
||||
}
|
||||
else {
|
||||
modified = modified
|
||||
.replace(reBracketProp, "['" + minNames[index] + "']")
|
||||
.replace(reDotProp, '.' + minNames[index])
|
||||
.replace(rePropColon, "'" + minNames[index] + "':")
|
||||
|
||||
// correct `value.source` in regexp branch of `_.clone`
|
||||
if (property == 'source') {
|
||||
modified = modified.replace("value['" + minNames[index] + "']", "value['source']");
|
||||
}
|
||||
}
|
||||
modified = modified
|
||||
.replace(reBracketProp, "['" + minNames[index] + "']")
|
||||
.replace(reDotProp, "['" + minNames[index] + "']")
|
||||
.replace(rePropColon, "$1'" + minNames[index] + "':");
|
||||
});
|
||||
|
||||
// replace with modified snippet
|
||||
@@ -379,7 +319,7 @@
|
||||
isIteratorTemplate = /var iteratorTemplate\b/.test(snippet),
|
||||
modified = snippet;
|
||||
|
||||
// add brackets to whitelisted properties so Closure Compiler won't mung them
|
||||
// add brackets to whitelisted properties so the Closure Compiler won't mung them
|
||||
modified = modified.replace(RegExp('\\.(' + iteratorOptions.join('|') + ')\\b', 'g'), "['$1']");
|
||||
|
||||
if (isCreateIterator) {
|
||||
@@ -407,17 +347,11 @@
|
||||
modified = modified.replace(RegExp('\\b' + property + '\\b', 'g'), minNames[index]);
|
||||
}
|
||||
else {
|
||||
if (property == 'array' || property == 'object') {
|
||||
// minify "array" and "object" sub property names
|
||||
modified = modified.replace(RegExp("'" + property + "'( *[\\]:])", 'g'), "'" + minNames[index] + "'$1");
|
||||
}
|
||||
else {
|
||||
// minify property name strings
|
||||
modified = modified.replace(RegExp("'" + property + "'", 'g'), "'" + minNames[index] + "'");
|
||||
// minify property names in regexes and accessors
|
||||
if (isCreateIterator) {
|
||||
modified = modified.replace(RegExp('([\\.|/])' + property + '\\b' , 'g'), '$1' + minNames[index]);
|
||||
}
|
||||
// minify property name strings
|
||||
modified = modified.replace(RegExp("'" + property + "'", 'g'), "'" + minNames[index] + "'");
|
||||
// minify property names in accessors
|
||||
if (isCreateIterator) {
|
||||
modified = modified.replace(RegExp('\\.' + property + '\\b' , 'g'), '.' + minNames[index]);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -440,8 +374,17 @@
|
||||
// was invoked directly (e.g. `node pre-compile.js source.js`) and write to
|
||||
// the same file
|
||||
(function() {
|
||||
var source = fs.readFileSync(process.argv[2], 'utf8');
|
||||
fs.writeFileSync(process.argv[2], preprocess(source), 'utf8');
|
||||
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');
|
||||
}());
|
||||
}
|
||||
}());
|
||||
|
||||
4667
doc/README.md
4667
doc/README.md
File diff suppressed because it is too large
Load Diff
@@ -20,9 +20,10 @@
|
||||
|
||||
// generate Markdown
|
||||
$markdown = docdown(array(
|
||||
'path' => '../' . $file,
|
||||
'title' => 'Lo-Dash <sup>v0.6.1</sup>',
|
||||
'url' => 'https://github.com/bestiejs/lodash/blob/master/lodash.js'
|
||||
'path' => '../' . $file,
|
||||
'title' => 'Lo-Dash <sup>v0.9.0</sup>',
|
||||
'toc' => 'categories',
|
||||
'url' => 'https://github.com/bestiejs/lodash/blob/master/lodash.js'
|
||||
));
|
||||
|
||||
// save to a .md file
|
||||
|
||||
76
lodash.min.js
vendored
76
lodash.min.js
vendored
@@ -1,41 +1,39 @@
|
||||
/*!
|
||||
Lo-Dash 0.6.1 lodash.com/license
|
||||
Underscore.js 1.3.3 github.com/documentcloud/underscore/blob/master/LICENSE
|
||||
Lo-Dash 0.9.0 lodash.com/license
|
||||
Underscore.js 1.4.2 underscorejs.org/LICENSE
|
||||
*/
|
||||
;(function(e,t){function s(e){return new o(e)}function o(e){if(e&&e._wrapped)return e;this._wrapped=e}function u(e,t,n){t||(t=0);var r=e.length,i=r-t>=(n||V),s=i?{}:e;if(i)for(var o=t-1;++o<r;)n=e[o]+"",(ft.call(s,n)?s[n]:s[n]=[]).push(e[o]);return function(e){if(i){var n=e+"";return ft.call(s,n)&&-1<k(s[n],e)}return-1<k(s,e,t)}}function a(){for(var e,t,n,s=-1,o=arguments.length,u={e:"",f:"",j:"",q:"",c:{d:""},m:{d:""}};++s<o;)for(t in e=arguments[s],e)n=(n=e[t])==r?"":n,/d|i/.test(t)?
|
||||
("string"==typeof n&&(n={b:n,l:n}),u.c[t]=n.b||"",u.m[t]=n.l||""):u[t]=n;e=u.a,t=/^[^,]+/.exec(e)[0],n=u.s,u.g=t,u.h=Lt,u.k=Ft,u.n=Mt,u.p=st,u.r=u.r!==i,u.s=n==r?It:n,u.o==r&&(u.o=Pt),u.f||(u.f="if(!"+t+")return u");if("d"!=t||!u.c.i)u.c=r;t="",u.s&&(t+="'use strict';"),t+="var i,A,j="+u.g+",u",u.j&&(t+="="+u.j),t+=";"+u.f+";"+u.q+";",u.c&&(t+="var l=j.length;i=-1;",u.m&&(t+="if(l>-1&&l===l>>>0){"),u.o&&(t+="if(z.call(j)==x){j=j.split('')}"),t+=u.c.d+";while(++i<l){A=j[i];"+u.c.i+"}",u.m&&(t+="}"
|
||||
));if(u.m){u.c?t+="else{":u.n&&(t+="var l=j.length;i=-1;if(l&&P(j)){while(++i<l){A=j[i+=''];"+u.m.i+"}}else{"),u.h||(t+="var v=typeof j=='function'&&r.call(j,'prototype');");if(u.k&&u.r)t+="var o=-1,p=Y[typeof j]?m(j):[],l=p.length;"+u.m.d+";while(++o<l){i=p[o];",u.h||(t+="if(!(v&&i=='prototype')){"),t+="A=j[i];"+u.m.i+"",u.h||(t+="}");else{t+=u.m.d+";for(i in j){";if(!u.h||u.r)t+="if(",u.h||(t+="!(v&&i=='prototype')"),!u.h&&u.r&&(t+="&&"),u.r&&(t+="g.call(j,i)"),t+="){";t+="A=j[i];"+u.m.i+";";if(!
|
||||
u.h||u.r)t+="}"}t+="}";if(u.h){t+="var f=j.constructor;";for(n=0;7>n;n++)t+="i='"+u.p[n]+"';if(","constructor"==u.p[n]&&(t+="!(f&&f.prototype===j)&&"),t+="g.call(j,i)){A=j[i];"+u.m.i+"}"}if(u.c||u.n)t+="}"}return t+=u.e+";return u",Function("D,E,F,I,e,K,g,h,N,P,R,T,U,k,X,Y,m,r,w,x,z","var G=function("+e+"){"+t+"};return G")(qt,q,_,f,at,un,ft,D,k,b,tn,w,E,p,xt,Wt,gt,ct,ht,Nt,pt)}function f(e,n){var r=e.b,i=n.b,e=e.a,n=n.a;return e===t?1:n===t?-1:e<n?-1:e>n?1:r<i?-1:1}function l(e,t){return ut[t]}function c
|
||||
(e){return"\\"+Xt[e]}function h(e){return Ut[e]}function p(e,t){return function(n,r,i){return e.call(t,n,r,i)}}function d(){}function v(e,t){if(e&&J.test(t))return"<e%-"+t+"%>";var n=ut.length;return ut[n]="'+__e("+t+")+'",ot+n}function m(e,t,n,i){return i?(e=ut.length,ut[e]="';"+i+";__p+='",ot+e):t?v(r,t):g(r,n)}function g(e,t){if(e&&J.test(t))return"<e%="+t+"%>";var n=ut.length;return ut[n]="'+((__t=("+t+"))==null?'':__t)+'",ot+n}function y(e){return zt[e]}function b(e){return pt.call(e)==yt}function w
|
||||
(e){return"function"==typeof e}function E(e,t){return e?e==U||e.__proto__==U&&(t||!b(e)):i}function S(e,t,s,o,u){if(e==r)return e;s&&(t=i),u||(u={d:r}),u.d==r&&(u.d=!(!R.clone&&!z.clone&&!W.clone));if(((s=Wt[typeof e])||u.d)&&e.clone&&w(e.clone))return u.d=r,e.clone(t);if(s){var a=pt.call(e);if(!Rt[a]||_t&&b(e))return e;var f=a==bt,s=f||(a==xt?E(e,n):s)}if(!s||!t)return s?f?ht.call(e):on({},e):e;s=e.constructor;switch(a){case wt:return new s(e==n);case Et:return new s(+e);case St:case Nt:return new
|
||||
s(e);case Tt:return s(e.source,Z.exec(e))}o||(o=[]);for(a=o.length;a--;)if(o[a].c==e)return o[a].d;var a=e.length,l=f?s(a):{};o.push({d:l,c:e});if(f)for(f=-1;++f<a;)l[f]=S(e[f],t,r,o,u);else an(e,function(e,n){l[n]=S(e,t,r,o,u)});return l}function x(e,t,s,o){if(e==r||t==r)return e===t;o||(o={value:r}),o.value==r&&(o.value=!(!R.isEqual&&!z.isEqual&&!W.isEqual));if(Wt[typeof e]||Wt[typeof t]||o.value){e._chain&&(e=e._wrapped),t._chain&&(t=t._wrapped);if(e.isEqual&&w(e.isEqual))return o.value=r,e.isEqual
|
||||
(t);if(t.isEqual&&w(t.isEqual))return o.value=r,t.isEqual(e)}if(e===t)return 0!==e||1/e==1/t;var u=pt.call(e);if(u!=pt.call(t))return i;switch(u){case wt:case Et:return+e==+t;case St:return e!=+e?t!=+t:0==e?1/e==1/t:e==+t;case Tt:case Nt:return e==t+""}var a=qt[u];if(_t&&!a&&(a=b(e))&&!b(t)||!a&&(u!=xt||Ht&&("function"!=typeof e.toString&&"string"==typeof (e+"")||"function"!=typeof t.toString&&"string"==typeof (t+""))))return i;s||(s=[]);for(u=s.length;u--;)if(s[u]==e)return n;var u=-1,f=n,l=0;s.
|
||||
push(e);if(a){l=e.length;if(f=l==t.length)for(;l--&&(f=x(e[l],t[l],s,o)););return f}a=e.constructor,f=t.constructor;if(a!=f&&(!w(a)||!(a instanceof a&&w(f)&&f instanceof f)))return i;for(var c in e)if(ft.call(e,c)&&(l++,!ft.call(t,c)||!x(e[c],t[c],s,o)))return i;for(c in t)if(ft.call(t,c)&&!(l--))return i;if(Lt)for(;7>++u;)if(c=st[u],ft.call(e,c)&&(!ft.call(t,c)||!x(e[c],t[c],s,o)))return i;return n}function T(e,t,n,r){if(!e)return n;var i=e.length,s=3>arguments.length;r&&(t=p(t,r));if(-1<i&&i===
|
||||
i>>>0){var o=Pt&&pt.call(e)==Nt?e.split(""):e;for(i&&s&&(n=o[--i]);i--;)n=t(n,o[i],i,e);return n}o=cn(e);for((i=o.length)&&s&&(n=e[o[--i]]);i--;)s=o[i],n=t(n,e[s],s,e);return n}function N(e,t,n){if(e)return t==r||n?e[0]:ht.call(e,0,t)}function C(e,t){var n=[];if(!e)return n;for(var r,i=-1,s=e.length;++i<s;)r=e[i],tn(r)?lt.apply(n,t?r:C(r)):n.push(r);return n}function k(e,t,n){if(!e)return-1;var r=-1,i=e.length;if(n){if("number"!=typeof n)return r=O(e,t),e[r]===t?r:-1;r=(0>n?Math.max(0,i+n):n)-1}for(
|
||||
;++r<i;)if(e[r]===t)return r;return-1}function L(e,t,n){var r=-Infinity,i=r;if(!e)return i;var s=-1,o=e.length;if(!t){for(;++s<o;)e[s]>i&&(i=e[s]);return i}for(n&&(t=p(t,n));++s<o;)n=t(e[s],s,e),n>r&&(r=n,i=e[s]);return i}function A(e,t,n){return e?ht.call(e,t==r||n?1:t):[]}function O(e,t,n,r){if(!e)return 0;var i=0,s=e.length;if(n){r&&(n=_(n,r));for(t=n(t);i<s;)r=i+s>>>1,n(e[r])<t?i=r+1:s=r}else for(;i<s;)r=i+s>>>1,e[r]<t?i=r+1:s=r;return i}function M(e,t,n,r){var s=[];if(!e)return s;var o=-1,u=
|
||||
e.length,a=[];"function"==typeof t&&(r=n,n=t,t=i);for(n?r&&(n=p(n,r)):n=D;++o<u;)if(r=n(e[o],o,e),t?!o||a[a.length-1]!==r:0>k(a,r))a.push(r),s.push(e[o]);return s}function _(e,t){function n(){var o=arguments,u=t;return i||(e=t[r]),s.length&&(o=o.length?s.concat(ht.call(o)):s),this instanceof n?(d.prototype=e.prototype,u=new d,(o=e.apply(u,o))&&Wt[typeof o]?o:u):e.apply(u,o)}var r,i=w(e);if(i){if(jt||dt&&2<arguments.length)return dt.call.apply(dt,arguments)}else r=t,t=e;var s=ht.call(arguments,2);
|
||||
return n}function D(e){return e}function P(e){wn(fn(e),function(t){var r=s[t]=e[t];o.prototype[t]=function(){var e=[this._wrapped];return arguments.length&<.apply(e,arguments),e=r.apply(s,e),this._chain&&(e=new o(e),e._chain=n),e}})}var n=!0,r=null,i=!1,H,B,j,F,I="object"==typeof exports&&exports&&("object"==typeof global&&global&&global==global.global&&(e=global),exports),q=Array.prototype,R=Boolean.prototype,U=Object.prototype,z=Number.prototype,W=String.prototype,X=0,V=30,$=e._,J=/[-+=!~*%&^<>|{(\/]|\[\D|\b(?:delete|in|instanceof|new|typeof|void)\b/
|
||||
,K=/&(?:amp|lt|gt|quot|#x27);/g,Q=/\b__p\+='';/g,G=/\b(__p\+=)''\+/g,Y=/(__e\(.*?\)|\b__t\))\+'';/g,Z=/\w*$/,et=/(?:__e|__t=)\(\s*(?![\d\s"']|this\.)/g,tt=RegExp("^"+(U.valueOf+"").replace(/[.*+?^=!:${}()|[\]\/\\]/g,"\\$&").replace(/valueOf|for [^\]]+/g,".+?")+"$"),nt=/__token__(\d+)/g,rt=/[&<>"']/g,it=/['\n\r\t\u2028\u2029\\]/g,st="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" "),ot="__token__",ut=[],at=q.concat,ft=U.hasOwnProperty,lt=q.push
|
||||
,ct=U.propertyIsEnumerable,ht=q.slice,pt=U.toString,dt=tt.test(dt=ht.bind)&&dt,vt=tt.test(vt=Array.isArray)&&vt,mt=e.isFinite,gt=tt.test(gt=Object.keys)&>,yt="[object Arguments]",bt="[object Array]",wt="[object Boolean]",Et="[object Date]",St="[object Number]",xt="[object Object]",Tt="[object RegExp]",Nt="[object String]",Ct=e.clearTimeout,kt=e.setTimeout,Lt,At,Ot,Mt=n;(function(){function e(){this.x=1}var t={0:1,length:1},n=[];e.prototype={valueOf:1,y:1};for(var r in new e)n.push(r);for(r in arguments
|
||||
)Mt=!r;Lt=4>(n+"").length,Ot="x"!=n[0],At=(n.splice.call(t,0,1),t[0])})(1);var _t=!b(arguments),Dt="x"!=ht.call("x")[0],Pt="xx"!="x"[0]+Object("x")[0];try{var Ht=("[object Object]",pt.call(e.document||0)==xt)}catch(Bt){}var jt=dt&&/\n|Opera/.test(dt+pt.call(e.opera)),Ft=gt&&/^.+$|true/.test(gt+!!e.attachEvent),It=!jt,qt={"[object Arguments]":n,"[object Array]":n,"[object Boolean]":i,"[object Date]":i,"[object Function]":i,"[object Number]":i,"[object Object]":i,"[object RegExp]":i,"[object String]"
|
||||
:n},Rt={"[object Arguments]":i,"[object Array]":n,"[object Boolean]":n,"[object Date]":n,"[object Function]":i,"[object Number]":n,"[object Object]":n,"[object RegExp]":n,"[object String]":n},Ut={"&":"&","<":"<",">":">",'"':""","'":"'"},zt={"&":"&","<":"<",">":">",""":'"',"'":"'"},Wt={"boolean":i,"function":n,object:n,number:i,string:i,"undefined":i,unknown:n},Xt={"\\":"\\","'":"'","\n":"n","\r":"r"," ":"t","\u2028":"u2028","\u2029":"u2029"};s.templateSettings=
|
||||
{escape:/<%-([\s\S]+?)%>/g,evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,variable:""};var Vt={a:"d,c,y",j:"d",q:"if(!c)c=h;else if(y)c=k(c,y)",i:"if(c(A,i,d)===false)return u"},$t={j:"{}",q:"var q;if(typeof c!='function'){var ii=c;c=function(A){return A[ii]}}else if(y)c=k(c,y)",i:"q=c(A,i,d);(g.call(u,q)?u[q]++:u[q]=1)"},Jt={r:i,a:"n,c,y",j:"{}",q:"var S=typeof c=='function';if(!S){var t=e.apply(E,arguments)}else if(y)c=k(c,y)",i:"if(S?!c(A,i,n):N(t,i)<0)u[i]=A"},Kt={j:"true",i:"if(!c(A,i,d))return!u"
|
||||
},Qt={r:i,s:i,a:"n",j:"n",q:"for(var a=1,b=arguments.length;a<b;a++){if(j=arguments[a]){",i:"u[i]=A",e:"}}"},Gt={j:"[]",i:"c(A,i,d)&&u.push(A)"},Yt={q:"if(y)c=k(c,y)"},Zt={i:{l:Vt.i}},en={j:"",f:"if(!d)return[]",d:{b:"u=Array(l)",l:"u="+(Ft?"Array(l)":"[]")},i:{b:"u[i]=c(A,i,d)",l:"u"+(Ft?"[o]=":".push")+"(c(A,i,d))"}};_t&&(b=function(e){return!!e&&!!ft.call(e,"callee")});var tn=vt||function(e){return pt.call(e)==bt};w(/x/)&&(w=function(e){return"[object Function]"==pt.call(e)}),E(Wt)||(E=function(
|
||||
e,t){var n=i;if(!e||"object"!=typeof e||!t&&b(e))return n;var r=e.constructor;return(!Ht||"function"==typeof e.toString||"string"!=typeof (e+""))&&(!w(r)||r instanceof r)?Ot?(un(e,function(t,r){return n=!ft.call(e,r),i}),n===i):(un(e,function(e,t){n=t}),n===i||ft.call(e,n)):n});var nn=a({a:"n",j:"[]",i:"u.push(i)"}),rn=a(Qt,{i:"if(u[i]==null)"+Qt.i}),sn=a(Jt),on=a(Qt),un=a(Vt,Yt,Zt,{r:i}),an=a(Vt,Yt,Zt),fn=a({r:i,a:"n",j:"[]",i:"if(T(A))u.push(i)",e:"u.sort()"}),ln=a({a:"A",j:"true",q:"var H=z.call(A),l=A.length;if(D[H]"+
|
||||
(_t?"||P(A)":"")+"||(H==X&&l>-1&&l===l>>>0&&T(A.splice)))return!l",i:{l:"return false"}}),cn=gt?function(e){var t=typeof e;return"function"==t&&ct.call(e,"prototype")?nn(e):e&&Wt[t]?gt(e):[]}:nn,hn=a(Qt,{a:"n,ee,O,ff",q:"var J,L,Q,gg,dd=O==U;if(!dd)ff=[];for(var a=1,b=dd?2:arguments.length;a<b;a++){if(j=arguments[a]){",i:"if(A&&((Q=R(A))||U(A))){L=false;gg=ff.length;while(gg--)if(L=ff[gg].c==A)break;if(L){u[i]=ff[gg].d}else{J=(J=u[i])&&Q?(R(J)?J:[]):(U(J)?J:{});ff.push({d:J,c:A});u[i]=G(J,A,U,ff)}}else if(A!=null)u[i]=A"
|
||||
}),pn=a(Jt,{q:"if(typeof c!='function'){var q,t=e.apply(E,arguments),l=t.length;for(i=1;i<l;i++){q=t[i];if(q in n)u[q]=n[q]}}else{if(y)c=k(c,y)",i:"if(c(A,i,n))u[i]=A",e:"}"}),dn=a({a:"n",j:"[]",i:"u.push(A)"}),vn=a({a:"d,hh",j:"false",o:i,d:{b:"if(z.call(d)==x)return d.indexOf(hh)>-1"},i:"if(A===hh)return true"}),mn=a(Vt,$t),gn=a(Vt,Kt),yn=a(Vt,Gt),bn=a(Vt,Yt,{j:"",i:"if(c(A,i,d))return A"}),wn=a(Vt,Yt),En=a(Vt,$t,{i:"q=c(A,i,d);(g.call(u,q)?u[q]:u[q]=[]).push(A)"}),Sn=a(en,{a:"d,V",q:"var C=w.call(arguments,2),S=typeof V=='function'"
|
||||
,i:{b:"u[i]=(S?V:A[V]).apply(A,C)",l:"u"+(Ft?"[o]=":".push")+"((S?V:A[V]).apply(A,C))"}}),xn=a(Vt,en),Tn=a(en,{a:"d,bb",i:{b:"u[i]=A[bb]",l:"u"+(Ft?"[o]=":".push")+"(A[bb])"}}),Nn=a({a:"d,c,B,y",j:"B",q:"var W=arguments.length<3;if(y)c=k(c,y)",d:{b:"if(W)u=j[++i]"},i:{b:"u=c(u,A,i,d)",l:"u=W?(W=false,A):c(u,A,i,d)"}}),Cn=a(Vt,Gt,{i:"!"+Gt.i}),kn=a(Vt,Kt,{j:"false",i:Kt.i.replace("!","")}),Ln=a(Vt,$t,en,{i:{b:"u[i]={a:c(A,i,d),b:i,d:A}",l:"u"+(Ft?"[o]=":".push")+"({a:c(A,i,d),b:i,d:A})"},e:"u.sort(I);l=u.length;while(l--)u[l]=u[l].d"
|
||||
}),An=a(Gt,{a:"d,aa",q:"var t=[];K(aa,function(A,q){t.push(q)});var cc=t.length",i:"for(var q,Z=true,s=0;s<cc;s++){q=t[s];if(!(Z=A[q]===aa[q]))break}Z&&u.push(A)"}),On=a({r:i,s:i,a:"n",j:"n",q:"var M=arguments,l=M.length;if(l>1){for(var i=1;i<l;i++)u[M[i]]=F(u[M[i]],u);return u}",i:"if(T(u[i]))u[i]=F(u[i],u)"});s.VERSION="0.6.1",s.after=function(e,t){return 1>e?t():function(){if(1>--e)return t.apply(this,arguments)}},s.bind=_,s.bindAll=On,s.chain=function(e){return e=new o(e),e._chain=n,e},s.clone=
|
||||
S,s.compact=function(e){var t=[];if(!e)return t;for(var n=-1,r=e.length;++n<r;)e[n]&&t.push(e[n]);return t},s.compose=function(){var e=arguments;return function(){for(var t=arguments,n=e.length;n--;)t=[e[n].apply(this,t)];return t[0]}},s.contains=vn,s.countBy=mn,s.debounce=function(e,t,n){function i(){a=r,n||e.apply(u,s)}var s,o,u,a;return function(){var r=n&&!a;return s=arguments,u=this,Ct(a),a=kt(i,t),r&&(o=e.apply(u,s)),o}},s.defaults=rn,s.defer=function(e){var n=ht.call(arguments,1);return kt
|
||||
(function(){return e.apply(t,n)},1)},s.delay=function(e,n){var r=ht.call(arguments,2);return kt(function(){return e.apply(t,r)},n)},s.difference=function(e){var t=[];if(!e)return t;for(var n=-1,r=e.length,i=at.apply(t,arguments),i=u(i,r);++n<r;)i(e[n])||t.push(e[n]);return t},s.drop=sn,s.escape=function(e){return e==r?"":(e+"").replace(rt,h)},s.every=gn,s.extend=on,s.filter=yn,s.find=bn,s.first=N,s.flatten=C,s.forEach=wn,s.forIn=un,s.forOwn=an,s.functions=fn,s.groupBy=En,s.has=function(e,t){return e?
|
||||
ft.call(e,t):i},s.identity=D,s.indexOf=k,s.initial=function(e,t,n){return e?ht.call(e,0,-(t==r||n?1:t)):[]},s.intersection=function(e){var t=[];if(!e)return t;var n,r=arguments.length,i=[],s=-1,o=e.length;e:for(;++s<o;)if(n=e[s],0>k(t,n)){for(var a=1;a<r;a++)if(!(i[a]||(i[a]=u(arguments[a])))(n))continue e;t.push(n)}return t},s.invoke=Sn,s.isArguments=b,s.isArray=tn,s.isBoolean=function(e){return e===n||e===i||pt.call(e)==wt},s.isElement=function(e){return e?1===e.nodeType:i},s.isEmpty=ln,s.isEqual=
|
||||
x,s.isFinite=function(e){return mt(e)&&pt.call(e)==St},s.isFunction=w,s.isNaN=function(e){return pt.call(e)==St&&e!=+e},s.isNull=function(e){return e===r},s.isObject=function(e){return e?Wt[typeof e]:i},s.isUndefined=function(e){return e===t},s.keys=cn,s.last=function(e,t,n){if(e){var i=e.length;return t==r||n?e[i-1]:ht.call(e,-t||i)}},s.lastIndexOf=function(e,t,n){if(!e)return-1;var r=e.length;for(n&&"number"==typeof n&&(r=(0>n?Math.max(0,r+n):Math.min(n,r-1))+1);r--;)if(e[r]===t)return r;return-1
|
||||
},s.map=xn,s.max=L,s.memoize=function(e,t){var n={};return function(){var r=t?t.apply(this,arguments):arguments[0];return ft.call(n,r)?n[r]:n[r]=e.apply(this,arguments)}},s.merge=hn,s.min=function(e,t,n){var r=Infinity,i=r;if(!e)return i;var s=-1,o=e.length;if(!t){for(;++s<o;)e[s]<i&&(i=e[s]);return i}for(n&&(t=p(t,n));++s<o;)n=t(e[s],s,e),n<r&&(r=n,i=e[s]);return i},s.mixin=P,s.noConflict=function(){return e._=$,this},s.once=function(e){var t,s=i;return function(){return s?t:(s=n,t=e.apply(this,
|
||||
arguments),e=r,t)}},s.partial=function(e){var t=ht.call(arguments,1),n=t.length;return function(){var r;return r=arguments,r.length&&(t.length=n,lt.apply(t,r)),r=1==t.length?e.call(this,t[0]):e.apply(this,t),t.length=n,r}},s.pick=pn,s.pluck=Tn,s.range=function(e,t,n){e=+e||0,n=+n||1,t==r&&(t=e,e=0);for(var i=-1,t=Math.max(0,Math.ceil((t-e)/n)),s=Array(t);++i<t;)s[i]=e,e+=n;return s},s.reduce=Nn,s.reduceRight=T,s.reject=Cn,s.rest=A,s.result=function(e,t){if(!e)return r;var n=e[t];return w(n)?e[t](
|
||||
):n},s.shuffle=function(e){if(!e)return[];for(var t,n=-1,r=e.length,i=Array(r);++n<r;)t=Math.floor(Math.random()*(n+1)),i[n]=i[t],i[t]=e[n];return i},s.size=function(e){if(!e)return 0;var t=pt.call(e),n=e.length;return qt[t]||_t&&b(e)||t==xt&&-1<n&&n===n>>>0&&w(e.splice)?n:cn(e).length},s.some=kn,s.sortBy=Ln,s.sortedIndex=O,s.tap=function(e,t){return t(e),e},s.template=function(e,t,n){n||(n={});var e=e+"",o,u;o=n.escape;var a=n.evaluate,f=n.interpolate,h=s.templateSettings,p=n=n.variable||h.variable
|
||||
;o==r&&(o=h.escape),a==r&&(a=h.evaluate||i),f==r&&(f=h.interpolate),o&&(e=e.replace(o,v)),f&&(e=e.replace(f,g)),a!=H&&(H=a,F=RegExp("<e%-([\\s\\S]+?)%>|<e%=([\\s\\S]+?)%>"+(a?"|"+a.source:""),"g")),o=ut.length,e=e.replace(F,m),o=o!=ut.length,e="__p += '"+e.replace(it,c).replace(nt,l)+"';",ut.length=0,p||(n=B||"obj",o?e="with("+n+"){"+e+"}":(n!=B&&(B=n,j=RegExp("(\\(\\s*)"+n+"\\."+n+"\\b","g")),e=e.replace(et,"$&"+n+".").replace(j,"$1__d"))),e=(o?e.replace(Q,""):e).replace(G,"$1").replace(Y,"$1;")
|
||||
,e="function("+n+"){"+(p?"":n+"||("+n+"={});")+"var __t,__p='',__e=_.escape"+(o?",__j=Array.prototype.join;function print(){__p+=__j.call(arguments,'')}":(p?"":",__d="+n+"."+n+"||"+n)+";")+e+"return __p}";try{u=Function("_","return "+e)(s)}catch(d){u=function(){throw d}}return t?u(t):(u.source=e,u)},s.throttle=function(e,t){function n(){a=new Date,u=r,e.apply(o,i)}var i,s,o,u,a=0;return function(){var r=new Date,f=t-(r-a);return i=arguments,o=this,0>=f?(a=r,s=e.apply(o,i)):u||(u=kt(n,f)),s}},s.times=
|
||||
function(e,t,n){var r=-1;if(n)for(;++r<e;)t.call(n,r);else for(;++r<e;)t(r)},s.toArray=function(e){if(!e)return[];if(e.toArray&&w(e.toArray))return e.toArray();var t=e.length;return-1<t&&t===t>>>0?(Dt?pt.call(e)==Nt:"string"==typeof e)?e.split(""):ht.call(e):dn(e)},s.unescape=function(e){return e==r?"":(e+"").replace(K,y)},s.union=function(){for(var e=-1,t=[],n=at.apply(t,arguments),r=n.length;++e<r;)0>k(t,n[e])&&t.push(n[e]);return t},s.uniq=M,s.uniqueId=function(e){var t=X++;return e?e+t:t},s.values=
|
||||
dn,s.where=An,s.without=function(e){var t=[];if(!e)return t;for(var n=-1,r=e.length,i=u(arguments,1,20);++n<r;)i(e[n])||t.push(e[n]);return t},s.wrap=function(e,t){return function(){var n=[e];return arguments.length&<.apply(n,arguments),t.apply(this,n)}},s.zip=function(e){if(!e)return[];for(var t=-1,n=L(Tn(arguments,"length")),r=Array(n);++t<n;)r[t]=Tn(arguments,t);return r},s.zipObject=function(e,t){if(!e)return{};var n=-1,r=e.length,i={};for(t||(t=[]);++n<r;)i[e[n]]=t[n];return i},s.all=gn,s.
|
||||
any=kn,s.collect=xn,s.detect=bn,s.each=wn,s.foldl=Nn,s.foldr=T,s.head=N,s.include=vn,s.inject=Nn,s.methods=fn,s.omit=sn,s.select=yn,s.tail=A,s.take=N,s.unique=M,wn({Date:Et,Number:St,RegExp:Tt,String:Nt},function(e,t){s["is"+t]=function(t){return pt.call(t)==e}}),o.prototype=s.prototype,P(s),o.prototype.chain=function(){return this._chain=n,this},o.prototype.value=function(){return this._wrapped},wn("pop push reverse shift sort splice unshift".split(" "),function(e){var t=q[e];o.prototype[e]=function(
|
||||
){var e=this._wrapped;return t.apply(e,arguments),At&&e.length===0&&delete e[0],this._chain&&(e=new o(e),e._chain=n),e}}),wn(["concat","join","slice"],function(e){var t=q[e];o.prototype[e]=function(){var e=t.apply(this._wrapped,arguments);return this._chain&&(e=new o(e),e._chain=n),e}}),typeof define=="function"&&typeof define.amd=="object"&&define.amd?(e._=s,define(function(){return s})):I?"object"==typeof module&&module&&module.t==I?(module.t=s)._=s:I._=s:e._=s})(this);
|
||||
;(function(e,t){function s(e){if(e&&e.__wrapped__)return e;if(!(this instanceof s))return new s(e);this.__wrapped__=e}function o(e,t,n){t||(t=0);var r=e.length,i=r-t>=(n||Q),s=i?{}:e;if(i)for(n=t-1;++n<r;){var o=e[n]+"";(dt.call(s,o)?s[o]:s[o]=[]).push(e[n])}return function(e){if(i){var n=e+"";return dt.call(s,n)&&-1<j(s[n],e)}return-1<j(s,e,t)}}function u(e,n){var r=e.b,i=n.b,e=e.a,n=n.a;if(e!==n){if(e>n||e===t)return 1;if(e<n||n===t)return-1}return r<i?-1:1}function a(e,t,n){function r(){var u=arguments
|
||||
,a=s?this:t;return i||(e=t[o]),n.length&&(u=u.length?n.concat(gt.call(u)):n),this instanceof r?(p.prototype=e.prototype,a=new p,(u=e.apply(a,u))&&Vt[typeof u]?u:a):e.apply(a,u)}var i=S(e),s=!n,o=e;return s&&(n=t),r}function f(e,n){return e?"function"!=typeof e?function(t){return t[e]}:n!==t?function(t,r,i){return e.call(n,t,r,i)}:e:U}function l(){for(var e={b:"",c:"",e:Pt,f:Wt,g:"",h:jt,i:qt,j:ft,k:"",l:n},t,r=0;t=arguments[r];r++)for(var i in t)e[i]=t[i];t=e.a,e.d=/^[^,]+/.exec(t)[0],r="var h,w,j="+
|
||||
e.d+",r="+e.d+";if(!"+e.d+")return r;"+e.k+";",e.b?(r+="var k=j.length;h=-1;if(typeof k=='number'){",e.i&&(r+="if(v.call(j)==t){j=j.split('')}"),r+="while(++h<k){w=j[h];"+e.b+"}}else {"):e.h&&(r+="var k=j.length;h=-1;if(k&&i(j)){while(++h<k){w=j[h+=''];"+e.g+"}}else {"),e.e||(r+="var s=typeof j=='function'&&q.call(j,'prototype');");if(e.f&&e.l)r+="var o=-1,p=n[typeof j]?l(j):[],k=p.length;while(++o<k){h=p[o];",e.e||(r+="if(!(s&&h=='prototype')){"),r+="w=j[h];"+e.g+"",e.e||(r+="}");else{r+="for(h in j){"
|
||||
;if(!e.e||e.l)r+="if(",e.e||(r+="!(s&&h=='prototype')"),!e.e&&e.l&&(r+="&&"),e.l&&(r+="g.call(j,h)"),r+="){";r+="w=j[h];"+e.g+";";if(!e.e||e.l)r+="}"}r+="}";if(e.e){r+="var f=j.constructor;";for(i=0;7>i;i++)r+="h='"+e.j[i]+"';if(","constructor"==e.j[i]&&(r+="!(f&&f.prototype===j)&&"),r+="g.call(j,h)){w=j[h];"+e.g+"}"}if(e.b||e.h)r+="}";return r+=e.c+";return r",Function("e,g,i,n,l,q,t,v","return function("+t+"){"+r+"}")(f,dt,v,Vt,St,mt,Dt,yt)}function c(e){return"\\"+$t[e]}function h(e){return Zt
|
||||
[e]}function p(){}function d(e){return en[e]}function v(e){return yt.call(e)==Ct}function m(e){var t=i;if(!e||"object"!=typeof e||v(e))return t;var n=e.constructor;return(!Rt||"function"==typeof e.toString||"string"!=typeof (e+""))&&(!S(n)||n instanceof n)?Ht?(Gt(e,function(e,n,r){return t=!dt.call(r,n),i}),t===i):(Gt(e,function(e,n){t=n}),t===i||dt.call(e,t)):t}function g(e){var t=[];return Yt(e,function(e,n){t.push(n)}),t}function y(e,t,n,s,o){if(e==r)return e;n&&(t=i);if(n=Vt[typeof e]){var u=
|
||||
yt.call(e);if(!Xt[u]||Ft&&v(e))return e;var a=u==kt,n=a||(u==Mt?sn(e):n)}if(!n||!t)return n?a?gt.call(e):nn({},e):e;n=e.constructor;switch(u){case Lt:case At:return new n(+e);case Ot:case Dt:return new n(e);case _t:return n(e.source,rt.exec(e))}s||(s=[]),o||(o=[]);for(u=s.length;u--;)if(s[u]==e)return o[u];var f=a?n(e.length):{};return s.push(e),o.push(f),(a?un:Yt)(e,function(e,n){f[n]=y(e,t,r,s,o)}),f}function b(e){var t=[];return Gt(e,function(e,n){S(e)&&t.push(n)}),t.sort()}function w(e){var t=
|
||||
{};return Yt(e,function(e,n){t[e]=n}),t}function E(e,t,s,o){if(e===t)return 0!==e||1/e==1/t;if(e==r||t==r)return e===t;var u=yt.call(e);if(u!=yt.call(t))return i;switch(u){case Lt:case At:return+e==+t;case Ot:return e!=+e?t!=+t:0==e?1/e==1/t:e==+t;case _t:case Dt:return e==t+""}var a=u==kt||u==Ct;if(Ft&&!a&&(a=v(e))&&!v(t))return i;if(!a){if(e.__wrapped__||t.__wrapped__)return E(e.__wrapped__||e,t.__wrapped__||t);if(u!=Mt||Rt&&("function"!=typeof e.toString&&"string"==typeof (e+"")||"function"!=typeof
|
||||
t.toString&&"string"==typeof (t+"")))return i;var u=e.constructor,f=t.constructor;if(u!=f&&(!S(u)||!(u instanceof u&&S(f)&&f instanceof f)))return i}s||(s=[]),o||(o=[]);for(u=s.length;u--;)if(s[u]==e)return o[u]==t;var u=-1,f=n,l=0;s.push(e),o.push(t);if(a){l=e.length;if(f=l==t.length)for(;l--&&(f=E(e[l],t[l],s,o)););return f}for(var c in e)if(dt.call(e,c)&&(l++,!dt.call(t,c)||!E(e[c],t[c],s,o)))return i;for(c in t)if(dt.call(t,c)&&!(l--))return i;if(Pt)for(;7>++u;)if(c=ft[u],dt.call(e,c)&&(!dt.call
|
||||
(t,c)||!E(e[c],t[c],s,o)))return i;return n}function S(e){return"function"==typeof e}function x(e,t,n){var i=arguments,s=0,o=2,u=i[3],a=i[4];n!==K&&(u=[],a=[],o=i.length);for(;++s<o;)Yt(i[s],function(t,n){var i,s,o;if(t&&((s=rn(t))||sn(t))){for(var f=u.length;f--;)if(i=u[f]==t)break;i?e[n]=a[f]:(u.push(t),a.push(o=(o=e[n],s)?rn(o)?o:[]:sn(o)?o:{}),e[n]=x(o,t,K,u,a))}else t!=r&&(e[n]=t)});return e}function T(e){var t=[];return Yt(e,function(e){t.push(e)}),t}function N(e,t){return"number"==typeof (
|
||||
e?e.length:0)?-1<(yt.call(e)==Dt?e.indexOf(t):j(e,t)):P(e,function(e){return e===t})}function C(e,t,r){var i=n,t=f(t,r);return un(e,function(e,n,r){return i=t(e,n,r)}),!!i}function k(e,t,n){var r=[],t=f(t,n);return un(e,function(e,n,i){t(e,n,i)&&r.push(e)}),r}function L(e,t,r){var i,t=f(t,r);return P(e,function(e,r,s){return t(e,r,s)&&(i=e,n)}),i}function A(e,t,n){var r=-1,i=e?e.length:0,s=Array("number"==typeof i?i:0),t=f(t,n);if(rn(e))for(;++r<i;)s[r]=t(e[r],r,e);else un(e,function(e,n,i){s[++r
|
||||
]=t(e,n,i)});return s}function O(e,t,n){var r=-Infinity,i=-1,s=e?e.length:0,o=r;if(t||"number"!=typeof s)t=f(t,n),un(e,function(e,n,i){n=t(e,n,i),n>r&&(r=n,o=e)});else for(;++i<s;)e[i]>o&&(o=e[i]);return o}function M(e,t){var n=[];return un(e,function(e){n.push(e[t])}),n}function _(e,t,n,r){var s=3>arguments.length,t=f(t,r);return un(e,function(e,r,o){n=s?(s=i,e):t(n,e,r,o)}),n}function D(e,t,n,r){var s=e,o=e?e.length:0,u=3>arguments.length;if("number"!=typeof o)var a=on(e),o=a.length;else qt&&yt
|
||||
.call(e)==Dt&&(s=e.split(""));return un(e,function(e,f,l){f=a?a[--o]:--o,n=u?(u=i,s[f]):t.call(r,n,s[f],f,l)}),n}function P(e,t,n){var r,t=f(t,n);return un(e,function(e,n,i){return!(r=t(e,n,i))}),!!r}function H(e,t,n){if(e)return t==r||n?e[0]:gt.call(e,0,t)}function B(e,t){for(var n=-1,r=e?e.length:0,i=[];++n<r;){var s=e[n];rn(s)?vt.apply(i,t?s:B(s)):i.push(s)}return i}function j(e,t,n){var r=-1,i=e?e.length:0;if("number"==typeof n)r=(0>n?xt(0,i+n):n||0)-1;else if(n)return r=I(e,t),e[r]===t?r:-1;
|
||||
for(;++r<i;)if(e[r]===t)return r;return-1}function F(e,t,n){return e?gt.call(e,t==r||n?1:t):[]}function I(e,t,n,r){for(var i=0,s=e?e.length:i,n=n?f(n,r):U,t=n(t);i<s;)r=i+s>>>1,n(e[r])<t?i=r+1:s=r;return i}function q(e,t,n,r){var s=-1,o=e?e.length:0,u=[],a=[];"function"==typeof t&&(r=n,n=t,t=i);for(n=f(n,r);++s<o;)if(r=n(e[s],s,e),t?!s||a[a.length-1]!==r:0>j(a,r))a.push(r),u.push(e[s]);return u}function R(e,t){return zt||bt&&2<arguments.length?bt.call.apply(bt,arguments):a(e,t,gt.call(arguments,2
|
||||
))}function U(e){return e}function z(e){un(b(e),function(t){var r=s[t]=e[t];s.prototype[t]=function(){var e=[this.__wrapped__];return vt.apply(e,arguments),e=r.apply(s,e),this.__chain__&&(e=new s(e),e.__chain__=n),e}})}var n=!0,r=null,i=!1,W="object"==typeof exports&&exports,X="object"==typeof global&&global;X.global===X&&(e=X);var V=[],$={},J=0,K={},Q=30,G=e._,Y=/[-?+=!~*%&^<>|{(\/]|\[\D|\b(?:delete|in|instanceof|new|typeof|void)\b/,Z=/&(?:amp|lt|gt|quot|#x27);/g,et=/\b__p\+='';/g,tt=/\b(__p\+=)''\+/g
|
||||
,nt=/(__e\(.*?\)|\b__t\))\+'';/g,rt=/\w*$/,it=/(?:__e|__t=)\(\s*(?![\d\s"']|this\.)/g,st=RegExp("^"+($.valueOf+"").replace(/[.*+?^=!:${}()|[\]\/\\]/g,"\\$&").replace(/valueOf|for [^\]]+/g,".+?")+"$"),ot=/($^)/,ut=/[&<>"']/g,at=/['\n\r\t\u2028\u2029\\]/g,ft="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" "),lt=Math.ceil,ct=V.concat,ht=Math.floor,pt=st.test(pt=Object.getPrototypeOf)&&pt,dt=$.hasOwnProperty,vt=V.push,mt=$.propertyIsEnumerable,gt=
|
||||
V.slice,yt=$.toString,bt=st.test(bt=gt.bind)&&bt,wt=st.test(wt=Array.isArray)&&wt,Et=e.isFinite,St=st.test(St=Object.keys)&&St,xt=Math.max,Tt=Math.min,Nt=Math.random,Ct="[object Arguments]",kt="[object Array]",Lt="[object Boolean]",At="[object Date]",Ot="[object Number]",Mt="[object Object]",_t="[object RegExp]",Dt="[object String]",Pt,Ht,Bt=(Bt={0:1,length:1},V.splice.call(Bt,0,1),Bt[0]),jt=n;(function(){function e(){this.x=1}var t=[];e.prototype={valueOf:1,y:1};for(var n in new e)t.push(n);for(
|
||||
n in arguments)jt=!n;Pt=!/valueOf/.test(t),Ht="x"!=t[0]})(1);var Ft=!v(arguments),It="x"!=gt.call("x")[0],qt="xx"!="x"[0]+Object("x")[0];try{var Rt=("[object Object]",yt.call(e.document||0)==Mt)}catch(Ut){}var zt=bt&&/\n|Opera/.test(bt+yt.call(e.opera)),Wt=St&&/^.+$|true/.test(St+!!e.attachEvent),Xt={};Xt[Ct]=Xt["[object Function]"]=i,Xt[kt]=Xt[Lt]=Xt[At]=Xt[Ot]=Xt[Mt]=Xt[_t]=Xt[Dt]=n;var Vt={"boolean":i,"function":n,object:n,number:i,string:i,"undefined":i},$t={"\\":"\\","'":"'","\n":"n","\r":"r"
|
||||
," ":"t","\u2028":"u2028","\u2029":"u2029"};s.templateSettings={escape:/<%-([\s\S]+?)%>/g,evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,variable:""};var Jt={a:"d,c,u",k:"c=e(c,u)",b:"if(c(w,h,d)===false)return r",g:"if(c(w,h,d)===false)return r"},Kt={l:i,a:"m",k:"for(var a=1,b=arguments.length;a<b;a++){if(j=arguments[a]){",g:"r[h]=w",c:"}}"},Qt={b:r};Ft&&(v=function(e){return e?dt.call(e,"callee"):i});var Gt=l(Jt,Qt,{l:i}),Yt=l(Jt,Qt),Zt={"&":"&","<":"<",">":">",'"':"""
|
||||
,"'":"'"},en=w(Zt),tn=l(Kt,{g:"if(r[h]==null)"+Kt.g}),nn=l(Kt),rn=wt||function(e){return yt.call(e)==kt};S(/x/)&&(S=function(e){return"[object Function]"==yt.call(e)});var sn=pt?function(e){if(!e||"object"!=typeof e)return i;var t=e.valueOf,n="function"==typeof t&&(n=pt(t))&&pt(n);return n?e==n||pt(e)==n&&!v(e):m(e)}:m,on=St?function(e){var t=typeof e;return"function"==t&&mt.call(e,"prototype")?g(e):e&&Vt[t]?St(e):[]}:g,un=l(Jt);s.VERSION="0.9.0",s.after=function(e,t){return 1>e?t():function(
|
||||
){if(1>--e)return t.apply(this,arguments)}},s.bind=R,s.bindAll=function(e){for(var t=arguments,n=1<t.length?0:(t=b(e),-1),r=t.length;++n<r;){var i=t[n];e[i]=R(e[i],e)}return e},s.chain=function(e){return e=new s(e),e.__chain__=n,e},s.clone=y,s.compact=function(e){for(var t=-1,n=e?e.length:0,r=[];++t<n;){var i=e[t];i&&r.push(i)}return r},s.compose=function(){var e=arguments;return function(){for(var t=arguments,n=e.length;n--;)t=[e[n].apply(this,t)];return t[0]}},s.contains=N,s.countBy=function(e,
|
||||
t,n){var r={},t=f(t,n);return un(e,function(e,n,i){n=t(e,n,i),dt.call(r,n)?r[n]++:r[n]=1}),r},s.debounce=function(e,t,n){function i(){a=r,n||(o=e.apply(u,s))}var s,o,u,a;return function(){var r=n&&!a;return s=arguments,u=this,clearTimeout(a),a=setTimeout(i,t),r&&(o=e.apply(u,s)),o}},s.defaults=tn,s.defer=function(e){var n=gt.call(arguments,1);return setTimeout(function(){e.apply(t,n)},1)},s.delay=function(e,n){var r=gt.call(arguments,2);return setTimeout(function(){e.apply(t,r)},n)},s.difference=
|
||||
function(e){for(var t=-1,n=e?e.length:0,r=ct.apply(V,arguments),r=o(r,n),i=[];++t<n;){var s=e[t];r(s)||i.push(s)}return i},s.escape=function(e){return e==r?"":(e+"").replace(ut,h)},s.every=C,s.extend=nn,s.filter=k,s.find=L,s.first=H,s.flatten=B,s.forEach=un,s.forIn=Gt,s.forOwn=Yt,s.functions=b,s.groupBy=function(e,t,n){var r={},t=f(t,n);return un(e,function(e,n,i){n=t(e,n,i),(dt.call(r,n)?r[n]:r[n]=[]).push(e)}),r},s.has=function(e,t){return e?dt.call(e,t):i},s.identity=U,s.indexOf=j,s.initial=function(
|
||||
e,t,n){return e?gt.call(e,0,-(t==r||n?1:t)):[]},s.intersection=function(e){var t=arguments,n=t.length,r={},i=[];return un(e,function(e){if(0>j(i,e)){for(var s=n;--s;)if(!(r[s]||(r[s]=o(t[s])))(e))return;i.push(e)}}),i},s.invert=w,s.invoke=function(e,t){var n=gt.call(arguments,2),r="function"==typeof t,i=[];return un(e,function(e){i.push((r?t:e[t]).apply(e,n))}),i},s.isArguments=v,s.isArray=rn,s.isBoolean=function(e){return e===n||e===i||yt.call(e)==Lt},s.isDate=function(e){return yt.call(e)==At},
|
||||
s.isElement=function(e){return e?1===e.nodeType:i},s.isEmpty=function(e){var t=n;if(!e)return t;var r=yt.call(e),s=e.length;return r==kt||r==Dt||r==Ct||Ft&&v(e)||r==Mt&&"number"==typeof s&&S(e.splice)?!s:(Yt(e,function(){return t=i}),t)},s.isEqual=E,s.isFinite=function(e){return Et(e?+e:parseFloat(e))},s.isFunction=S,s.isNaN=function(e){return yt.call(e)==Ot&&e!=+e},s.isNull=function(e){return e===r},s.isNumber=function(e){return yt.call(e)==Ot},s.isObject=function(e){return e?Vt[typeof e]:i},s.isPlainObject=
|
||||
sn,s.isRegExp=function(e){return yt.call(e)==_t},s.isString=function(e){return yt.call(e)==Dt},s.isUndefined=function(e){return e===t},s.keys=on,s.last=function(e,t,n){if(e){var i=e.length;return t==r||n?e[i-1]:gt.call(e,-t||i)}},s.lastIndexOf=function(e,t,n){var r=e?e.length:0;for("number"==typeof n&&(r=(0>n?xt(0,r+n):Tt(n,r-1))+1);r--;)if(e[r]===t)return r;return-1},s.lateBind=function(e,t){return a(t,e,gt.call(arguments,2))},s.map=A,s.max=O,s.memoize=function(e,t){var n={};return function(){var r=
|
||||
t?t.apply(this,arguments):arguments[0];return dt.call(n,r)?n[r]:n[r]=e.apply(this,arguments)}},s.merge=x,s.min=function(e,t,n){var r=Infinity,i=-1,s=e?e.length:0,o=r;if(t||"number"!=typeof s)t=f(t,n),un(e,function(e,n,i){n=t(e,n,i),n<r&&(r=n,o=e)});else for(;++i<s;)e[i]<o&&(o=e[i]);return o},s.mixin=z,s.noConflict=function(){return e._=G,this},s.object=function(e,t){for(var n=-1,r=e?e.length:0,i={};++n<r;){var s=e[n];t?i[s]=t[n]:i[s[0]]=s[1]}return i},s.omit=function(e,t,n){var r="function"==typeof
|
||||
t,i={};if(r)t=f(t,n);else var s=ct.apply(V,arguments);return Gt(e,function(e,n,o){if(r?!t(e,n,o):0>j(s,n,1))i[n]=e}),i},s.once=function(e){var t,s=i;return function(){return s?t:(s=n,t=e.apply(this,arguments),e=r,t)}},s.pairs=function(e){var t=[];return Yt(e,function(e,n){t.push([n,e])}),t},s.partial=function(e){return a(e,gt.call(arguments,1))},s.pick=function(e,t,n){var r={};if("function"!=typeof t)for(var i=0,s=ct.apply(V,arguments),o=s.length;++i<o;){var u=s[i];u in e&&(r[u]=e[u])}else t=f(t,
|
||||
n),Gt(e,function(e,n,i){t(e,n,i)&&(r[n]=e)});return r},s.pluck=M,s.random=function(e,t){return e==r&&t==r&&(t=1),e=+e||0,t==r&&(t=e,e=0),e+ht(Nt()*((+t||0)-e+1))},s.range=function(e,t,n){e=+e||0,n=+n||1,t==r&&(t=e,e=0);for(var i=-1,t=xt(0,lt((t-e)/n)),s=Array(t);++i<t;)s[i]=e,e+=n;return s},s.reduce=_,s.reduceRight=D,s.reject=function(e,t,n){return t=f(t,n),k(e,function(e,n,r){return!t(e,n,r)})},s.rest=F,s.result=function(e,t){var n=e?e[t]:r;return S(n)?e[t]():n},s.shuffle=function(e){var t=-1,n=
|
||||
Array(e?e.length:0);return un(e,function(e){var r=ht(Nt()*(++t+1));n[t]=n[r],n[r]=e}),n},s.size=function(e){var t=e?e.length:0;return"number"==typeof t?t:on(e).length},s.some=P,s.sortBy=function(e,t,n){var r=[],t=f(t,n);un(e,function(e,n,i){r.push({a:t(e,n,i),b:n,c:e})}),e=r.length;for(r.sort(u);e--;)r[e]=r[e].c;return r},s.sortedIndex=I,s.tap=function(e,t){return t(e),e},s.template=function(e,t,n){e||(e=""),n||(n={});var r,i,o=0,u=s.templateSettings,a="__p += '",f=n.variable||u.variable,l=f;e.replace
|
||||
(RegExp((n.escape||u.escape||ot).source+"|"+(n.interpolate||u.interpolate||ot).source+"|"+(n.evaluate||u.evaluate||ot).source+"|$","g"),function(t,n,i,s,u){a+=e.slice(o,u).replace(at,c),a+=n?"'+__e("+n+")+'":s?"';"+s+";__p+='":i?"'+((__t=("+i+"))==null?'':__t)+'":"",r||(r=s||Y.test(n||i)),o=u+t.length}),a+="';",l||(f="obj",r?a="with("+f+"){"+a+"}":(n=RegExp("(\\(\\s*)"+f+"\\."+f+"\\b","g"),a=a.replace(it,"$&"+f+".").replace(n,"$1__d"))),a=(r?a.replace(et,""):a).replace(tt,"$1").replace(nt,"$1;"),
|
||||
a="function("+f+"){"+(l?"":f+"||("+f+"={});")+"var __t,__p='',__e=_.escape"+(r?",__j=[].join;function print(){__p+=__j.call(arguments,'')}":(l?"":",__d="+f+"."+f+"||"+f)+";")+a+"return __p}";try{i=Function("_","return "+a)(s)}catch(h){throw h.source=a,h}return t?i(t):(i.source=a,i)},s.throttle=function(e,t){function n(){a=new Date,u=r,s=e.apply(o,i)}var i,s,o,u,a=0;return function(){var r=new Date,f=t-(r-a);return i=arguments,o=this,0>=f?(clearTimeout(u),a=r,s=e.apply(o,i)):u||(u=setTimeout
|
||||
(n,f)),s}},s.times=function(e,t,n){for(var e=+e||0,r=-1,i=Array(e);++r<e;)i[r]=t.call(n,r);return i},s.toArray=function(e){return e&&"number"==typeof e.length?(It?yt.call(e)==Dt:"string"==typeof e)?e.split(""):gt.call(e):T(e)},s.unescape=function(e){return e==r?"":(e+"").replace(Z,d)},s.union=function(){for(var e=-1,t=ct.apply(V,arguments),n=t.length,r=[];++e<n;){var i=t[e];0>j(r,i)&&r.push(i)}return r},s.uniq=q,s.uniqueId=function(e){var t=J++;return e?e+t:t},s.values=T,s.where=function(e,t){var n=
|
||||
[];return Gt(t,function(e,t){n.push(t)}),k(e,function(e){for(var r=n.length;r--;){var i=e[n[r]]===t[n[r]];if(!i)break}return!!i})},s.without=function(e){for(var t=-1,n=e?e.length:0,r=o(arguments,1,20),i=[];++t<n;){var s=e[t];r(s)||i.push(s)}return i},s.wrap=function(e,t){return function(){var n=[e];return vt.apply(n,arguments),t.apply(this,n)}},s.zip=function(e){for(var t=-1,n=e?O(M(arguments,"length")):0,r=Array(n);++t<n;)r[t]=M(arguments,t);return r},s.all=C,s.any=P,s.collect=A,s.detect=L,s.drop=
|
||||
F,s.each=un,s.foldl=_,s.foldr=D,s.head=H,s.include=N,s.inject=_,s.methods=b,s.select=k,s.tail=F,s.take=H,s.unique=q,z(s),s.prototype.chain=function(){return this.__chain__=n,this},s.prototype.value=function(){return this.__wrapped__},un("pop push reverse shift sort splice unshift".split(" "),function(e){var t=V[e];s.prototype[e]=function(){var e=this.__wrapped__;return t.apply(e,arguments),Bt&&e.length===0&&delete e[0],this.__chain__&&(e=new s(e),e.__chain__=n),e}}),un(["concat","join","slice"],function(
|
||||
e){var t=V[e];s.prototype[e]=function(){var e=t.apply(this.__wrapped__,arguments);return this.__chain__&&(e=new s(e),e.__chain__=n),e}}),typeof define=="function"&&typeof define.amd=="object"&&define.amd?(e._=s,define(function(){return s})):W?"object"==typeof module&&module&&module.exports==W?(module.exports=s)._=s:W._=s:e._=s})(this);
|
||||
31
lodash.underscore.min.js
vendored
Normal file
31
lodash.underscore.min.js
vendored
Normal file
@@ -0,0 +1,31 @@
|
||||
/*!
|
||||
Lo-Dash 0.9.0 lodash.com/license
|
||||
Underscore.js 1.4.2 underscorejs.org/LICENSE
|
||||
*/
|
||||
;(function(e,t){function s(e,t,n){var r;if(!e)return e;var t=p(t,n),i=e.length,n=-1;if("number"==typeof i)for(;++n<i&&(r=e[n],t(r,n,e)!==J););else for(n in e)if(it.call(e,n)&&(r=e[n],t(r,n,e)===J))break;return e}function o(e){var t,n,r=e;if(!e)return e;for(var i=1,s=arguments.length;i<s;i++)if(r=arguments[i])for(t in r)n=r[t],e[t]=n;return e}function u(e){var t,n,i=e;if(!e)return e;for(var s=1,o=arguments.length;s<o;s++)if(i=arguments[s])for(t in i)n=i[t],e[t]==r&&(e[t]=n);return e}function a(e,t)
|
||||
{var n,r;if(e)for(n in t=p(t),e)if(it.call(e,n)&&(r=e[n],t(r,n,e)===J))break}function f(e,t){var n,r;if(e)for(n in t=p(t),e)if(r=e[n],t(r,n,e)===J)break}function l(e){if(e&&e.__wrapped__)return e;if(!(this instanceof l))return new l(e);this.__wrapped__=e}function c(e,n){var r=e.b,i=n.b,e=e.a,n=n.a;if(e!==n){if(e>n||e===t)return 1;if(e<n||n===t)return-1}return r<i?-1:1}function h(e,t,n){function r(){var i=arguments,s=t;return n.length&&(i=i.length?n.concat(ot.call(i)):n),this instanceof r?(m.prototype=
|
||||
e.prototype,s=new m,(i=e.apply(s,i))&&Tt[typeof i]?i:s):e.apply(s,i)}return r}function p(e,n){return e?"function"!=typeof e?function(t){return t[e]}:n!==t?function(t,r,i){return e.call(n,t,r,i)}:e:U}function d(e){return"\\"+Nt[e]}function v(e){return Ct[e]}function m(){}function g(e){return kt[e]}function y(e){var t=[];return a(e,function(e,n){t.push(n)}),t}function b(e){var t=[];return f(e,function(e,n){S(e)&&t.push(n)}),t.sort()}function w(e){var t={};return a(e,function(e,n){t[e]=n}),t}function E
|
||||
(e,t,s,o){if(e===t)return 0!==e||1/e==1/t;if(e==r||t==r)return e===t;var u=ut.call(e);if(u!=ut.call(t))return i;switch(u){case mt:case gt:return+e==+t;case yt:return e!=+e?t!=+t:0==e?1/e==1/t:e==+t;case wt:case Et:return e==t+""}var a=u==vt;if(!a){if(e.__wrapped__||t.__wrapped__)return E(e.__wrapped__||e,t.__wrapped__||t);if(u!=bt)return i;var u=e.constructor,f=t.constructor;if(u!=f&&(!S(u)||!(u instanceof u&&S(f)&&f instanceof f)))return i}s||(s=[]),o||(o=[]);for(u=s.length;u--;)if(s[u]==e)return o
|
||||
[u]==t;u=n,f=0,s.push(e),o.push(t);if(a){f=e.length;if(u=f==t.length)for(;f--&&(u=E(e[f],t[f],s,o)););return u}for(var l in e)if(it.call(e,l)&&(f++,!it.call(t,l)||!E(e[l],t[l],s,o)))return i;for(l in t)if(it.call(t,l)&&!(f--))return i;return n}function S(e){return"function"==typeof e}function x(e){return ut.call(e)==Et}function T(e){var t=[];return a(e,function(e){t.push(e)}),t}function N(e,t){return"number"==typeof (e?e.length:0)?-1<j(e,t):P(e,function(e){return e===t})}function C(e,t,r){var i=n
|
||||
,t=p(t,r);return s(e,function(e,n,r){return!(i=t(e,n,r))&&J}),!!i}function k(e,t,n){var r=[],t=p(t,n);return s(e,function(e,n,i){t(e,n,i)&&r.push(e)}),r}function L(e,t,r){var i,t=p(t,r);return P(e,function(e,r,s){return t(e,r,s)&&(i=e,n)}),i}function A(e,t,n){var r=-1,i=e?e.length:0,o=Array("number"==typeof i?i:0),t=p(t,n);if(Lt(e))for(;++r<i;)o[r]=t(e[r],r,e);else s(e,function(e,n,i){o[++r]=t(e,n,i)});return o}function O(e,t,n){var r=-Infinity,i=-1,o=e?e.length:0,u=r;if(t||"number"!=typeof o)t=p
|
||||
(t,n),s(e,function(e,n,i){n=t(e,n,i),n>r&&(r=n,u=e)});else for(;++i<o;)e[i]>u&&(u=e[i]);return u}function M(e,t){var n=[];return s(e,function(e){n.push(e[t])}),n}function _(e,t,n,r){var o=3>arguments.length,t=p(t,r);return s(e,function(e,r,s){n=o?(o=i,e):t(n,e,r,s)}),n}function D(e,t,n,r){var o=e?e.length:0,u=3>arguments.length;if("number"!=typeof o)var a=At(e),o=a.length;return s(e,function(s,f,l){f=a?a[--o]:--o,n=u?(u=i,e[f]):t.call(r,n,e[f],f,l)}),n}function P(e,t,n){var r,t=p(t,n);return s(e,
|
||||
function(e,n,i){return(r=t(e,n,i))&&J}),!!r}function H(e,t,n){if(e)return t==r||n?e[0]:ot.call(e,0,t)}function B(e,t){for(var n=-1,r=e?e.length:0,i=[];++n<r;){var s=e[n];Lt(s)?st.apply(i,t?s:B(s)):i.push(s)}return i}function j(e,t,n){var r=-1,i=e?e.length:0;if("number"==typeof n)r=(0>n?ht(0,i+n):n||0)-1;else if(n)return r=I(e,t),e[r]===t?r:-1;for(;++r<i;)if(e[r]===t)return r;return-1}function F(e,t,n){return e?ot.call(e,t==r||n?1:t):[]}function I(e,t,n,r){for(var i=0,s=e?e.length:i,n=n?p(n,r):U,t=
|
||||
n(t);i<s;)r=i+s>>>1,n(e[r])<t?i=r+1:s=r;return i}function q(e,t,n,r){for(var i=-1,s=e?e.length:0,o=[],u=[],n=p(n,r);++i<s;)if(r=n(e[i],i,e),t?!i||u[u.length-1]!==r:0>j(u,r))u.push(r),o.push(e[i]);return o}function R(e,t){return xt||at&&2<arguments.length?at.call.apply(at,arguments):h(e,t,ot.call(arguments,2))}function U(e){return e}function z(e){s(b(e),function(t){var r=l[t]=e[t];l.prototype[t]=function(){var e=[this.__wrapped__];return st.apply(e,arguments),e=r.apply(l,e),this.__chain__&&(e=new
|
||||
l(e),e.__chain__=n),e}})}var n=!0,r=null,i=!1,W="object"==typeof exports&&exports,X="object"==typeof global&&global;X.global===X&&(e=X);var V=[],X={},$=0,J={},K=e._,Q=/&(?:amp|lt|gt|quot|#x27);/g,G=RegExp("^"+(X.valueOf+"").replace(/[.*+?^=!:${}()|[\]\/\\]/g,"\\$&").replace(/valueOf|for [^\]]+/g,".+?")+"$"),Y=/($^)/,Z=/[&<>"']/g,et=/['\n\r\t\u2028\u2029\\]/g,tt=Math.ceil,nt=V.concat,rt=Math.floor,it=X.hasOwnProperty,st=V.push,ot=V.slice,ut=X.toString,at=G.test(at=ot.bind)&&at,ft=G.test(ft=Array.isArray
|
||||
)&&ft,lt=e.isFinite,ct=G.test(ct=Object.keys)&&ct,ht=Math.max,pt=Math.min,dt=Math.random,vt="[object Array]",mt="[object Boolean]",gt="[object Date]",yt="[object Number]",bt="[object Object]",wt="[object RegExp]",Et="[object String]",St=(St={0:1,length:1},V.splice.call(St,0,1),St[0]),xt=at&&/\n|Opera/.test(at+ut.call(e.opera)),Tt={"boolean":i,"function":n,object:n,number:i,string:i,"undefined":i},Nt={"\\":"\\","'":"'","\n":"n","\r":"r"," ":"t","\u2028":"u2028","\u2029":"u2029"};l.templateSettings=
|
||||
{escape:/<%-([\s\S]+?)%>/g,evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,variable:""},l.isArguments=function(e){return"[object Arguments]"==ut.call(e)},l.isArguments(arguments)||(l.isArguments=function(e){return e?it.call(e,"callee"):i});var Ct={"&":"&","<":"<",">":">",'"':""","'":"'"},kt=w(Ct),Lt=ft||function(e){return ut.call(e)==vt};S(/x/)&&(S=function(e){return"[object Function]"==ut.call(e)});var At=ct?function(e){return e&&Tt[typeof e]?ct(e):[]}:y;l.VERSION="0.9.0"
|
||||
,l.after=function(e,t){return 1>e?t():function(){if(1>--e)return t.apply(this,arguments)}},l.bind=R,l.bindAll=function(e){for(var t=arguments,n=1<t.length?0:(t=b(e),-1),r=t.length;++n<r;){var i=t[n];e[i]=R(e[i],e)}return e},l.chain=function(e){return e=new l(e),e.__chain__=n,e},l.clone=function(e){return e&&Tt[typeof e]?Lt(e)?ot.call(e):o({},e):e},l.compact=function(e){for(var t=-1,n=e?e.length:0,r=[];++t<n;){var i=e[t];i&&r.push(i)}return r},l.compose=function(){var e=arguments;return function()
|
||||
{for(var t=arguments,n=e.length;n--;)t=[e[n].apply(this,t)];return t[0]}},l.contains=N,l.countBy=function(e,t,n){var r={},t=p(t,n);return s(e,function(e,n,i){n=t(e,n,i),it.call(r,n)?r[n]++:r[n]=1}),r},l.debounce=function(e,t,n){function i(){a=r,n||(o=e.apply(u,s))}var s,o,u,a;return function(){var r=n&&!a;return s=arguments,u=this,clearTimeout(a),a=setTimeout(i,t),r&&(o=e.apply(u,s)),o}},l.defaults=u,l.defer=function(e){var n=ot.call(arguments,1);return setTimeout(function(){e.apply(t,n)},1)},l.delay=
|
||||
function(e,n){var r=ot.call(arguments,2);return setTimeout(function(){e.apply(t,r)},n)},l.difference=function(e){for(var t=-1,n=e.length,r=nt.apply(V,arguments),i=[];++t<n;){var s=e[t];0>j(r,s,n)&&i.push(s)}return i},l.escape=function(e){return e==r?"":(e+"").replace(Z,v)},l.every=C,l.extend=o,l.filter=k,l.find=L,l.first=H,l.flatten=B,l.forEach=s,l.functions=b,l.groupBy=function(e,t,n){var r={},t=p(t,n);return s(e,function(e,n,i){n=t(e,n,i),(it.call(r,n)?r[n]:r[n]=[]).push(e)}),r},l.has=function(
|
||||
e,t){return e?it.call(e,t):i},l.identity=U,l.indexOf=j,l.initial=function(e,t,n){return e?ot.call(e,0,-(t==r||n?1:t)):[]},l.intersection=function(e){var t=arguments,n=t.length,r=[];return s(e,function(e){if(0>j(r,e)){for(var i=n;--i;)if(0>j(t[i],e))return;r.push(e)}}),r},l.invert=w,l.invoke=function(e,t){var n=ot.call(arguments,2),r="function"==typeof t,i=[];return s(e,function(e){i.push((r?t:e[t]).apply(e,n))}),i},l.isArray=Lt,l.isBoolean=function(e){return e===n||e===i||ut.call(e)==mt},l.isDate=
|
||||
function(e){return ut.call(e)==gt},l.isElement=function(e){return e?1===e.nodeType:i},l.isEmpty=function(e){if(!e)return n;if(Lt(e)||x(e))return!e.length;for(var t in e)if(it.call(e,t))return i;return n},l.isEqual=E,l.isFinite=function(e){return lt(e?+e:parseFloat(e))},l.isFunction=S,l.isNaN=function(e){return ut.call(e)==yt&&e!=+e},l.isNull=function(e){return e===r},l.isNumber=function(e){return ut.call(e)==yt},l.isObject=function(e){return e?Tt[typeof e]:i},l.isRegExp=function(e){return ut.call
|
||||
(e)==wt},l.isString=x,l.isUndefined=function(e){return e===t},l.keys=At,l.last=function(e,t,n){if(e){var i=e.length;return t==r||n?e[i-1]:ot.call(e,-t||i)}},l.lastIndexOf=function(e,t,n){var r=e?e.length:0;for("number"==typeof n&&(r=(0>n?ht(0,r+n):pt(n,r-1))+1);r--;)if(e[r]===t)return r;return-1},l.map=A,l.max=O,l.memoize=function(e,t){var n={};return function(){var r=t?t.apply(this,arguments):arguments[0];return it.call(n,r)?n[r]:n[r]=e.apply(this,arguments)}},l.min=function(e,t,n){var r=Infinity
|
||||
,i=-1,o=e?e.length:0,u=r;if(t||"number"!=typeof o)t=p(t,n),s(e,function(e,n,i){n=t(e,n,i),n<r&&(r=n,u=e)});else for(;++i<o;)e[i]<u&&(u=e[i]);return u},l.mixin=z,l.noConflict=function(){return e._=K,this},l.object=function(e,t){for(var n=-1,r=e?e.length:0,i={};++n<r;){var s=e[n];t?i[s]=t[n]:i[s[0]]=s[1]}return i},l.omit=function(e){var t=nt.apply(V,arguments),n={};return f(e,function(e,r){0>j(t,r,1)&&(n[r]=e)}),n},l.once=function(e){var t,s=i;return function(){return s?t:(s=n,t=e.apply(this,arguments
|
||||
),e=r,t)}},l.pairs=function(e){var t=[];return a(e,function(e,n){t.push([n,e])}),t},l.pick=function(e){for(var t=0,n=nt.apply(V,arguments),r=n.length,i={};++t<r;){var s=n[t];s in e&&(i[s]=e[s])}return i},l.pluck=M,l.random=function(e,t){return e==r&&t==r&&(t=1),e=+e||0,t==r&&(t=e,e=0),e+rt(dt()*((+t||0)-e+1))},l.range=function(e,t,n){e=+e||0,n=+n||1,t==r&&(t=e,e=0);for(var i=-1,t=ht(0,tt((t-e)/n)),s=Array(t);++i<t;)s[i]=e,e+=n;return s},l.reduce=_,l.reduceRight=D,l.reject=function(e,t,n){return t=
|
||||
p(t,n),k(e,function(e,n,r){return!t(e,n,r)})},l.rest=F,l.result=function(e,t){var n=e?e[t]:r;return S(n)?e[t]():n},l.shuffle=function(e){var t=-1,n=Array(e?e.length:0);return s(e,function(e){var r=rt(dt()*(++t+1));n[t]=n[r],n[r]=e}),n},l.size=function(e){var t=e?e.length:0;return"number"==typeof t?t:At(e).length},l.some=P,l.sortBy=function(e,t,n){var r=[],t=p(t,n);s(e,function(e,n,i){r.push({a:t(e,n,i),b:n,c:e})}),e=r.length;for(r.sort(c);e--;)r[e]=r[e].c;return r},l.sortedIndex=I,l.tap=function(
|
||||
e,t){return t(e),e},l.template=function(e,t,n){e||(e="");var n=u({},n,l.templateSettings),r=0,i="__p += '",s=n.variable;e.replace(RegExp((n.escape||Y).source+"|"+(n.interpolate||Y).source+"|"+(n.evaluate||Y).source+"|$","g"),function(t,n,s,o,u){i+=e.slice(r,u).replace(et,d),i+=n?"'+_['escape']("+n+")+'":o?"';"+o+";__p+='":s?"'+((__t=("+s+"))==null?'':__t)+'":"",r=u+t.length}),i+="';",s||(s="obj",i="with("+s+"||{}){"+i+"}"),i="function("+s+"){var __t,__p='',__j=[].join;function print(){__p+=__j.call(arguments,'')}"+
|
||||
i+"return __p}";try{var o=Function("_","return "+i)(l)}catch(a){throw a.source=i,a}return t?o(t):(o.source=i,o)},l.throttle=function(e,t){function n(){a=new Date,u=r,s=e.apply(o,i)}var i,s,o,u,a=0;return function(){var r=new Date,f=t-(r-a);return i=arguments,o=this,0>=f?(clearTimeout(u),a=r,s=e.apply(o,i)):u||(u=setTimeout(n,f)),s}},l.times=function(e,t,n){for(var e=+e||0,r=-1,i=Array(e);++r<e;)i[r]=t.call(n,r);return i},l.toArray=function(e){return e&&"number"==typeof e.length?"string"==typeof e?
|
||||
e.split(""):ot.call(e):T(e)},l.unescape=function(e){return e==r?"":(e+"").replace(Q,g)},l.union=function(){for(var e=-1,t=nt.apply(V,arguments),n=t.length,r=[];++e<n;){var i=t[e];0>j(r,i)&&r.push(i)}return r},l.uniq=q,l.uniqueId=function(e){var t=$++;return e?e+t:t},l.values=T,l.where=function(e,t){var n=[];return f(t,function(e,t){n.push(t)}),k(e,function(e){for(var r=n.length;r--;){var i=e[n[r]]===t[n[r]];if(!i)break}return!!i})},l.without=function(e){for(var t=-1,n=e.length,r=[];++t<n;){var i=
|
||||
e[t];0>j(arguments,i,1)&&r.push(i)}return r},l.wrap=function(e,t){return function(){var n=[e];return st.apply(n,arguments),t.apply(this,n)}},l.zip=function(e){for(var t=-1,n=e?O(M(arguments,"length")):0,r=Array(n);++t<n;)r[t]=M(arguments,t);return r},l.all=C,l.any=P,l.collect=A,l.detect=L,l.drop=F,l.each=s,l.foldl=_,l.foldr=D,l.head=H,l.include=N,l.inject=_,l.methods=b,l.select=k,l.tail=F,l.take=H,l.unique=q,z(l),l.prototype.chain=function(){return this.__chain__=n,this},l.prototype.value=function(
|
||||
){return this.__wrapped__},s("pop push reverse shift sort splice unshift".split(" "),function(e){var t=V[e];l.prototype[e]=function(){var e=this.__wrapped__;return t.apply(e,arguments),St&&e.length===0&&delete e[0],this.__chain__&&(e=new l(e),e.__chain__=n),e}}),s(["concat","join","slice"],function(e){var t=V[e];l.prototype[e]=function(){var e=t.apply(this.__wrapped__,arguments);return this.__chain__&&(e=new l(e),e.__chain__=n),e}}),W?"object"==typeof module&&module&&module.exports==W?(module.exports=
|
||||
l)._=l:W._=l:e._=l})(this);
|
||||
12
package.json
12
package.json
@@ -1,9 +1,9 @@
|
||||
{
|
||||
"name": "lodash",
|
||||
"version": "0.6.1",
|
||||
"version": "0.9.0",
|
||||
"description": "A drop-in replacement for Underscore.js delivering performance, bug fixes, and additional features.",
|
||||
"homepage": "http://lodash.com",
|
||||
"main": "lodash",
|
||||
"main": "./lodash",
|
||||
"keywords": [
|
||||
"browser",
|
||||
"client",
|
||||
@@ -24,6 +24,9 @@
|
||||
"email": "john.david.dalton@gmail.com",
|
||||
"web": "http://allyoucanleet.com/"
|
||||
},
|
||||
"dependencies": {
|
||||
"tar": "~0.1.13"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/bestiejs/lodash/issues"
|
||||
},
|
||||
@@ -43,10 +46,11 @@
|
||||
"rhino"
|
||||
],
|
||||
"jam": {
|
||||
"main": "lodash.min.js"
|
||||
"main": "./lodash.js"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "node build",
|
||||
"test": "node test/test"
|
||||
"test": "node test/test && node test/test-build",
|
||||
"install": "node build/post-install"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,17 +13,34 @@
|
||||
position: absolute;
|
||||
left: -9999em;
|
||||
}
|
||||
#FirebugUI {
|
||||
top: 2em;
|
||||
}
|
||||
#perf-toolbar {
|
||||
background-color: #EEE;
|
||||
color: #5E740B;
|
||||
font-family: "Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial, sans-serif;
|
||||
font-size: small;
|
||||
padding: 0.5em 0 0.5em 2em;
|
||||
overflow: hidden;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<script src="../lodash.min.js"></script>
|
||||
<script>
|
||||
var lodash = _.noConflict();
|
||||
</script>
|
||||
<script src="../vendor/underscore/underscore-min.js"></script>
|
||||
<div id="perf-toolbar"></div>
|
||||
<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="perf-ui.js"></script>
|
||||
<script>
|
||||
document.write('<script src="../' + ui.buildPath + '"><\/script>');
|
||||
</script>
|
||||
<script>
|
||||
var lodash = _.noConflict();
|
||||
</script>
|
||||
<script>
|
||||
document.write('<script src="../' + ui.otherPath + '"><\/script>');
|
||||
</script>
|
||||
<script src="perf.js"></script>
|
||||
<script>
|
||||
(function() {
|
||||
@@ -39,7 +56,12 @@
|
||||
if (!fbCommandLine) {
|
||||
return setTimeout(init, 15);
|
||||
}
|
||||
fbUI.style.height = fbDoc.body.style.height = fbDoc.documentElement.style.height = '100%';
|
||||
fbUI.style.height = (
|
||||
Math.max(document.documentElement.clientHeight, document.body.clientHeight) -
|
||||
document.getElementById('perf-toolbar').clientHeight
|
||||
) + 'px';
|
||||
|
||||
fbDoc.body.style.height = fbDoc.documentElement.style.height = '100%';
|
||||
setTimeout(run, 15);
|
||||
}
|
||||
|
||||
|
||||
130
perf/perf-ui.js
Normal file
130
perf/perf-ui.js
Normal file
@@ -0,0 +1,130 @@
|
||||
;(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 'lodash.js';
|
||||
case 'lodash-underscore': return 'lodash.underscore.min.js';
|
||||
case 'lodash-custom': return 'lodash.custom.min.js';
|
||||
}
|
||||
return 'lodash.min.js';
|
||||
}());
|
||||
|
||||
// expose other library file path
|
||||
ui.otherPath = (function() {
|
||||
switch (other) {
|
||||
case 'lodash-dev': return 'lodash.js';
|
||||
case 'lodash-prod': return 'lodash.min.js';
|
||||
case 'lodash-underscore': return '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-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-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-underscore': return 2;
|
||||
case 'lodash-custom': return 3;
|
||||
}
|
||||
return 1;
|
||||
}());
|
||||
|
||||
otherList.selectedIndex = (function() {
|
||||
switch (other) {
|
||||
case 'underscore-dev': return 0;
|
||||
case 'lodash-dev': return 2;
|
||||
case 'lodash-prod': return 3;
|
||||
case 'lodash-underscore': return 4;
|
||||
case 'lodash-custom': return 5;
|
||||
}
|
||||
return 1;
|
||||
}());
|
||||
|
||||
addListener(buildList, 'change', eventHandler);
|
||||
addListener(otherList, 'change', eventHandler);
|
||||
});
|
||||
|
||||
// expose `ui`
|
||||
window.ui = ui;
|
||||
|
||||
}(this));
|
||||
671
perf/perf.js
671
perf/perf.js
File diff suppressed because it is too large
Load Diff
@@ -3,14 +3,11 @@
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Backbone Test Suite</title>
|
||||
<link rel="stylesheet" href="../vendor/backbone/test/vendor/qunit.css">
|
||||
<link rel="stylesheet" href="../vendor/qunit/qunit/qunit.css">
|
||||
<style>
|
||||
body > #qunit-header {
|
||||
display: none;
|
||||
}
|
||||
#jslitmus {
|
||||
display: none;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
@@ -21,15 +18,22 @@
|
||||
<h1>Test</h1>
|
||||
</div>
|
||||
</div>
|
||||
<script src="../vendor/backbone/test/vendor/json2.js"></script>
|
||||
<script src="../vendor/backbone/test/vendor/jquery-1.7.1.js"></script>
|
||||
<script src="../vendor/backbone/test/vendor/qunit.js"></script>
|
||||
<script src="../vendor/backbone/test/vendor/jslitmus.js"></script>
|
||||
<script src="../vendor/json3/lib/json3.js"></script>
|
||||
<script src="../vendor/jquery/jquery.js"></script>
|
||||
<script src="../vendor/platform.js/platform.js"></script>
|
||||
<script>
|
||||
// avoid syntax errors for `QUnit.throws` in older Firefoxes
|
||||
document.write(platform.name == 'Firefox' && /^1\b/.test(platform.version)
|
||||
? '<script src="../vendor/qunit/qunit/qunit-1.8.0.js"><\/script>'
|
||||
: '<script src="../vendor/qunit/qunit/qunit.js"><\/script>'
|
||||
);
|
||||
</script>
|
||||
<script src="test-ui.js"></script>
|
||||
<script>
|
||||
document.write('<script src="../' + QUnit.config.lodashFilename + '.js"><\/script>');
|
||||
document.write('<script src="../' + ui.buildPath + '"><\/script>');
|
||||
</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>
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
Object.keys = function() { return []; };
|
||||
|
||||
// load Lo-Dash and expose it to the bad `Object.keys` shim
|
||||
document.write('<script src="../' + QUnit.config.lodashFilename + '.js"><\/script>');
|
||||
document.write('<script src="../' + ui.buildPath + '"><\/script>');
|
||||
</script>
|
||||
<script>
|
||||
// store Lo-Dash to test for bad shim detection
|
||||
@@ -32,11 +32,8 @@
|
||||
Object.keys = Object._keys;
|
||||
delete Object._keys;
|
||||
|
||||
// set to test `_.noConflict`
|
||||
_ = 1;
|
||||
|
||||
// load Lo-Dash again to overwrite the existing `_` value
|
||||
document.write('<script src="../' + QUnit.config.lodashFilename + '.js"><\/script>');
|
||||
document.write('<script src="../' + ui.buildPath + '"><\/script>');
|
||||
|
||||
// load test.js if not using require.js
|
||||
document.write(QUnit.urlParams.norequire
|
||||
@@ -47,23 +44,40 @@
|
||||
<script>
|
||||
// load Lo-Dash as a module
|
||||
var lodashModule,
|
||||
shimmedModule,
|
||||
underscoreModule;
|
||||
|
||||
window.require && require({
|
||||
'baseUrl': '../vendor/requirejs/',
|
||||
'urlArgs': 't=' + (+new Date),
|
||||
'paths': {
|
||||
'lodash': '../../' + QUnit.config.lodashFilename,
|
||||
'underscore': './../../' + QUnit.config.lodashFilename
|
||||
window.require && require(
|
||||
(function() {
|
||||
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': '_'
|
||||
}
|
||||
}
|
||||
};
|
||||
}()),
|
||||
['lodash', 'shimmed', 'underscore'], function(lodash, shimmed, underscore) {
|
||||
if (lodash && lodash.noConflict) {
|
||||
lodashModule = lodash.noConflict();
|
||||
lodashModule.moduleName = 'lodash';
|
||||
}
|
||||
if (shimmed.noConflict) {
|
||||
shimmedModule = shimmed.noConflict();
|
||||
shimmedModule.moduleName = 'shimmed';
|
||||
}
|
||||
if (underscore && underscore.noConflict) {
|
||||
underscoreModule = underscore.noConflict();
|
||||
underscoreModule.moduleName = 'underscore';
|
||||
}
|
||||
},
|
||||
['lodash', 'underscore'], function(lodash, underscore) {
|
||||
lodashModule = lodash.noConflict();
|
||||
lodashModule.moduleName = 'lodash';
|
||||
|
||||
underscoreModule = underscore.noConflict();
|
||||
underscoreModule.moduleName = 'underscore';
|
||||
|
||||
require(['test.js']);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
cd "$(dirname "$0")"
|
||||
for cmd in rhino ringo narwhal node; do
|
||||
echo ""
|
||||
echo "Testing in $cmd..."
|
||||
$cmd test.js
|
||||
echo ""
|
||||
echo "Testing in $cmd..."
|
||||
$cmd test.js
|
||||
done
|
||||
|
||||
echo ""
|
||||
echo "Testing build..."
|
||||
node test-build.js
|
||||
|
||||
echo ""
|
||||
echo "Testing in a browser..."
|
||||
open index.html
|
||||
|
||||
3
test/template/a.jst
Normal file
3
test/template/a.jst
Normal file
@@ -0,0 +1,3 @@
|
||||
<ul>
|
||||
<% _.forEach(people, function(name) { %><li><%= name %></li><% }); %>
|
||||
</ul>
|
||||
1
test/template/b.jst
Normal file
1
test/template/b.jst
Normal file
@@ -0,0 +1 @@
|
||||
<% print("Hello " + epithet); %>.
|
||||
1
test/template/c.tpl
Normal file
1
test/template/c.tpl
Normal file
@@ -0,0 +1 @@
|
||||
Hello {{ name }}!
|
||||
1034
test/test-build.js
Normal file
1034
test/test-build.js
Normal file
File diff suppressed because it is too large
Load Diff
@@ -10,16 +10,20 @@
|
||||
/** A flag to determine if RequireJS should be loaded */
|
||||
var norequire = /[?&]norequire=true(?:&|$)/.test(location.search);
|
||||
|
||||
/** The `ui` object */
|
||||
var ui = {};
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
// assign `QUnit.config` properties
|
||||
QUnit.config.lodashFilename = (function() {
|
||||
// expose Lo-Dash build file path
|
||||
ui.buildPath = (function() {
|
||||
switch (build) {
|
||||
case 'prod': return 'lodash.min';
|
||||
case 'custom': return 'lodash.custom.min';
|
||||
case 'custom-debug': return 'lodash.custom';
|
||||
case 'lodash-prod': return 'lodash.min.js';
|
||||
case 'lodash-underscore': return 'lodash.underscore.min.js';
|
||||
case 'lodash-custom': return 'lodash.custom.min.js';
|
||||
case 'lodash-custom-debug': return 'lodash.custom.js';
|
||||
}
|
||||
return 'lodash';
|
||||
return 'lodash.js';
|
||||
}());
|
||||
|
||||
// assign `QUnit.urlParams` properties
|
||||
@@ -28,7 +32,7 @@
|
||||
'norequire': norequire
|
||||
});
|
||||
|
||||
// initialize the build dropdown
|
||||
// initialize controls
|
||||
addEvent(window, 'load', function() {
|
||||
function eventHandler(event) {
|
||||
var search = location.search.replace(/^\?|&?(?:build|norequire)=[^&]*&?/g, '');
|
||||
@@ -39,52 +43,60 @@
|
||||
}
|
||||
location.href =
|
||||
location.href.split('?')[0] + '?' +
|
||||
(search ? search + '&' : '') + 'build=' +
|
||||
dropdown[dropdown.selectedIndex].value +
|
||||
(search ? search + '&' : '') +
|
||||
'build=' + buildList[buildList.selectedIndex].value +
|
||||
(checkbox.checked ? '&norequire=true' : '');
|
||||
}
|
||||
|
||||
function init() {
|
||||
var toolbar = document.getElementById('qunit-testrunner-toolbar');
|
||||
if (toolbar) {
|
||||
toolbar.appendChild(label1);
|
||||
toolbar.appendChild(label2);
|
||||
toolbar.appendChild(span1);
|
||||
toolbar.appendChild(span2);
|
||||
|
||||
dropdown.selectedIndex = (function() {
|
||||
buildList.selectedIndex = (function() {
|
||||
switch (build) {
|
||||
case 'prod': return 1;
|
||||
case 'custom': return 2;
|
||||
case 'custom-debug': return 3;
|
||||
case 'lodash-prod': return 1;
|
||||
case 'lodash-underscore': return 2;
|
||||
case 'lodash-custom': return 3;
|
||||
case 'lodash-custom-debug': return 4;
|
||||
}
|
||||
return 0;
|
||||
}());
|
||||
|
||||
checkbox.checked = norequire;
|
||||
addEvent(checkbox, 'click', eventHandler);
|
||||
addEvent(dropdown, 'change', eventHandler);
|
||||
addEvent(buildList, 'change', eventHandler);
|
||||
}
|
||||
else {
|
||||
setTimeout(init, 15);
|
||||
}
|
||||
}
|
||||
|
||||
var label1 = document.createElement('label');
|
||||
label1.innerHTML =
|
||||
'<input name="norequire" type="checkbox">No RequireJS';
|
||||
var span1 = document.createElement('span');
|
||||
span1.innerHTML =
|
||||
'<input id="qunit-norequire" type="checkbox">' +
|
||||
'<label for="qunit-norequire">No RequireJS</label>';
|
||||
|
||||
var label2 = document.createElement('label');
|
||||
label2.innerHTML = ' ' +
|
||||
'<select name="build">' +
|
||||
'<option value="dev">Developement</option>' +
|
||||
'<option value="prod">Production</option>' +
|
||||
'<option value="custom">Custom</option>' +
|
||||
'<option value="custom-debug">Custom (debug)</option>' +
|
||||
'</select> Build';
|
||||
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-custom">Custom</option>' +
|
||||
'<option value="lodash-custom-debug">Custom (debug)</option>' +
|
||||
'</select>';
|
||||
|
||||
var checkbox = label1.firstChild,
|
||||
dropdown = label2.getElementsByTagName('select')[0];
|
||||
var checkbox = span1.firstChild,
|
||||
buildList = span2.lastChild;
|
||||
|
||||
init();
|
||||
});
|
||||
|
||||
// expose `ui`
|
||||
window.ui = ui;
|
||||
|
||||
}(this));
|
||||
|
||||
622
test/test.js
622
test/test.js
@@ -41,6 +41,14 @@
|
||||
/** Shortcut used to make object properties immutable */
|
||||
var freeze = Object.freeze;
|
||||
|
||||
/** Used to set property descriptors */
|
||||
var setDescriptor = (function(fn) {
|
||||
try {
|
||||
var o = {};
|
||||
return fn(o, o, o) && fn;
|
||||
} catch(e) { }
|
||||
}(Object.defineProperty));
|
||||
|
||||
/** Shortcut used to convert array-like objects to arrays */
|
||||
var slice = [].slice;
|
||||
|
||||
@@ -83,21 +91,28 @@
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
// add object from iframe
|
||||
(function() {
|
||||
if (!window.document) {
|
||||
return;
|
||||
}
|
||||
var body = document.body,
|
||||
iframe = document.createElement('iframe');
|
||||
|
||||
iframe.frameBorder = iframe.height = iframe.width = 0;
|
||||
body.appendChild(iframe);
|
||||
var idoc = (idoc = iframe.contentDocument || iframe.contentWindow).document || idoc;
|
||||
idoc.write("<script>parent._._object = { 'a': 1, 'b': 2, 'c': 3 };<\/script>");
|
||||
idoc.close();
|
||||
}());
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
// explicitly call `QUnit.module()` instead of `module()`
|
||||
// in case we are in a CLI environment
|
||||
QUnit.module('lodash');
|
||||
|
||||
(function() {
|
||||
// ensure this test is executed before any other template tests to avoid false positives
|
||||
test('should initialize `reEvaluateDelimiter` correctly (test with production build)', function() {
|
||||
var data = { 'a': [1, 2] },
|
||||
settings = _.templateSettings;
|
||||
|
||||
_.templateSettings = { 'interpolate': /\{\{(.+?)\}\}/g };
|
||||
equal(_.template('{{ a.join(",") }}', data), '1,2');
|
||||
_.templateSettings = settings;
|
||||
});
|
||||
|
||||
test('supports loading lodash.js as the "lodash" module', function() {
|
||||
if (window.document && window.require) {
|
||||
equal((lodashModule || {}).moduleName, 'lodash');
|
||||
@@ -106,6 +121,14 @@
|
||||
}
|
||||
});
|
||||
|
||||
test('supports loading lodash.js with the Require.js "shim" configuration option', function() {
|
||||
if (window.document && window.require) {
|
||||
equal((shimmedModule || {}).moduleName, 'shimmed');
|
||||
} else {
|
||||
skipTest();
|
||||
}
|
||||
});
|
||||
|
||||
test('supports loading lodash.js as the "underscore" module', function() {
|
||||
if (window.document && window.require) {
|
||||
equal((underscoreModule || {}).moduleName, 'underscore');
|
||||
@@ -143,30 +166,13 @@
|
||||
QUnit.module('lodash.bind');
|
||||
|
||||
(function() {
|
||||
test('should correctly append array arguments to partially applied arguments (test in IE < 9)', function() {
|
||||
test('should append array arguments to partially applied arguments (test in IE < 9)', function() {
|
||||
var args,
|
||||
bound = _.bind(function() { args = slice.call(arguments); }, {}, 'a');
|
||||
|
||||
bound(['b'], 'c');
|
||||
deepEqual(args, ['a', ['b'], 'c']);
|
||||
});
|
||||
|
||||
test('supports lazy bind', function() {
|
||||
var object = {
|
||||
'name': 'moe',
|
||||
'greet': function(greeting) {
|
||||
return greeting + ': ' + this.name;
|
||||
}
|
||||
};
|
||||
|
||||
var func = _.bind(object, 'greet', 'hi');
|
||||
equal(func(), 'hi: moe');
|
||||
|
||||
object.greet = function(greeting) {
|
||||
return greeting + ' ' + this.name + '!';
|
||||
};
|
||||
equal(func(), 'hi moe!');
|
||||
});
|
||||
}());
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
@@ -191,6 +197,7 @@
|
||||
'boolean object': Object(false),
|
||||
'an object': { 'a': 0, 'b': 1, 'c': 3 },
|
||||
'an object with object values': { 'a': /a/, 'b': ['B'], 'c': { 'C': 1 } },
|
||||
'an object from another document': _._object || {},
|
||||
'null': null,
|
||||
'a number': 3,
|
||||
'a number object': Object(3),
|
||||
@@ -203,14 +210,10 @@
|
||||
objects['an array'].length = 5;
|
||||
|
||||
_.forOwn(objects, function(object, key) {
|
||||
test('should deep clone ' + key + ' correctly', function() {
|
||||
test('should deep clone ' + key, function() {
|
||||
var clone = _.clone(object, true);
|
||||
ok(_.isEqual(object, clone));
|
||||
|
||||
if (object == null) {
|
||||
equal(clone, object);
|
||||
} else {
|
||||
deepEqual(clone.valueOf(), object.valueOf());
|
||||
}
|
||||
if (_.isObject(object)) {
|
||||
ok(clone !== object);
|
||||
} else {
|
||||
@@ -246,19 +249,6 @@
|
||||
ok(clone.bar.b === clone.foo.b && clone === clone.foo.b.foo.c && clone !== object);
|
||||
});
|
||||
|
||||
test('should clone using Klass#clone', function() {
|
||||
var object = new Klass;
|
||||
Klass.prototype.clone = function() { return new Klass; };
|
||||
|
||||
var clone = _.clone(object);
|
||||
ok(clone !== object && clone instanceof Klass);
|
||||
|
||||
clone = _.clone(object, true);
|
||||
ok(clone !== object && clone instanceof Klass);
|
||||
|
||||
delete Klass.prototype.clone;
|
||||
});
|
||||
|
||||
test('should clone problem JScript properties (test in IE < 9)', function() {
|
||||
deepEqual(_.clone(shadowed), shadowed);
|
||||
ok(_.clone(shadowed) != shadowed);
|
||||
@@ -304,7 +294,17 @@
|
||||
QUnit.module('lodash.debounce');
|
||||
|
||||
(function() {
|
||||
test('subsequent "immediate" debounced calls should return the result of the first call', function() {
|
||||
asyncTest('subsequent debounced calls return the last `func` result', function() {
|
||||
var debounced = _.debounce(function(value) { return value; }, 100);
|
||||
debounced('x');
|
||||
|
||||
setTimeout(function() {
|
||||
equal(debounced('y'), 'x');
|
||||
QUnit.start();
|
||||
}, 220);
|
||||
});
|
||||
|
||||
test('subsequent "immediate" debounced calls return the last `func` result', function() {
|
||||
var debounced = _.debounce(function(value) { return value; }, 100, true),
|
||||
result = [debounced('x'), debounced('y')];
|
||||
|
||||
@@ -317,7 +317,7 @@
|
||||
QUnit.module('lodash.difference');
|
||||
|
||||
(function() {
|
||||
test('should work correctly when using `cachedContains`', function() {
|
||||
test('should work when using `cachedContains`', function() {
|
||||
var array1 = _.range(27),
|
||||
array2 = array1.slice(),
|
||||
a = {},
|
||||
@@ -333,65 +333,6 @@
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
QUnit.module('lodash.drop');
|
||||
|
||||
(function() {
|
||||
var object = { 'a': 1, 'b': 2 },
|
||||
actual = { 'b': 2 };
|
||||
|
||||
test('should accept individual property names', function() {
|
||||
deepEqual(_.drop(object, 'a'), actual);
|
||||
});
|
||||
|
||||
test('should accept an array of property names', function() {
|
||||
deepEqual(_.drop(object, ['a', 'c']), actual);
|
||||
});
|
||||
|
||||
test('should accept mixes of individual and arrays of property names', function() {
|
||||
deepEqual(_.drop(object, ['a'], 'c'), actual);
|
||||
});
|
||||
|
||||
test('should iterate over inherited properties', function() {
|
||||
function Foo() {}
|
||||
Foo.prototype = object;
|
||||
|
||||
deepEqual(_.drop(new Foo, 'a'), actual);
|
||||
});
|
||||
|
||||
test('should work with a `callback` argument', function() {
|
||||
var actual = _.drop(object, function(value) {
|
||||
return value == 1;
|
||||
});
|
||||
|
||||
deepEqual(actual, { 'b': 2 });
|
||||
});
|
||||
|
||||
test('should pass the correct `callback` arguments', function() {
|
||||
var args,
|
||||
lastKey = _.keys(object).pop();
|
||||
|
||||
var expected = lastKey == 'b'
|
||||
? [1, 'a', object]
|
||||
: [2, 'b', object];
|
||||
|
||||
_.drop(object, function() {
|
||||
args || (args = slice.call(arguments));
|
||||
});
|
||||
|
||||
deepEqual(args, expected);
|
||||
});
|
||||
|
||||
test('should correct set the `this` binding', function() {
|
||||
var actual = _.drop(object, function(value) {
|
||||
return value == this.a;
|
||||
}, { 'a': 1 });
|
||||
|
||||
deepEqual(actual, { 'b': 2 });
|
||||
});
|
||||
}());
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
QUnit.module('lodash.escape');
|
||||
|
||||
(function() {
|
||||
@@ -435,11 +376,12 @@
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
QUnit.module('strict mode checks');
|
||||
|
||||
_.each(['bindAll', 'defaults', 'extend'], function(methodName) {
|
||||
var func = _[methodName];
|
||||
QUnit.module('lodash.' + methodName + ' strict mode checks');
|
||||
|
||||
test('should not throw strict mode errors', function() {
|
||||
test('lodash.' + methodName + ' should not throw strict mode errors', function() {
|
||||
var object = { 'a': null, 'b': function(){} },
|
||||
pass = true;
|
||||
|
||||
@@ -523,18 +465,6 @@
|
||||
equal(_.forEach(collection, Boolean), collection);
|
||||
});
|
||||
|
||||
test('should treat array-like object with invalid `length` as a regular object', function() {
|
||||
var keys = [],
|
||||
object = { 'length': -1 };
|
||||
|
||||
_.forEach(object, function(value, key) { keys.push(key); });
|
||||
deepEqual(keys, ['length']);
|
||||
|
||||
keys = []; object.length = Math.pow(2, 32);
|
||||
_.forEach(object, function(value, key) { keys.push(key); });
|
||||
deepEqual(keys, ['length']);
|
||||
});
|
||||
|
||||
_.each({
|
||||
'literal': 'abc',
|
||||
'object': Object('abc')
|
||||
@@ -586,17 +516,18 @@
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
QUnit.module('object iteration bugs');
|
||||
|
||||
_.each(['forEach', 'forIn', 'forOwn'], function(methodName) {
|
||||
var func = _[methodName];
|
||||
QUnit.module('lodash.' + methodName + ' iteration bugs');
|
||||
|
||||
test('fixes the JScript [[DontEnum]] bug (test in IE < 9)', function() {
|
||||
test('lodash.' + methodName + ' fixes the JScript [[DontEnum]] bug (test in IE < 9)', function() {
|
||||
var keys = [];
|
||||
func(shadowed, function(value, key) { keys.push(key); });
|
||||
deepEqual(keys.sort(), shadowedKeys);
|
||||
});
|
||||
|
||||
test('skips the prototype property of functions (test in Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1)', function() {
|
||||
test('lodash.' + methodName + ' skips the prototype property of functions (test in Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1)', function() {
|
||||
function Foo() {}
|
||||
Foo.prototype.a = 1;
|
||||
|
||||
@@ -613,11 +544,14 @@
|
||||
});
|
||||
});
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
QUnit.module('exit early');
|
||||
|
||||
_.each(['forEach', 'forIn', 'forOwn'], function(methodName) {
|
||||
var func = _[methodName];
|
||||
QUnit.module('lodash.' + methodName + ' can exit early');
|
||||
|
||||
test('can exit early when iterating arrays', function() {
|
||||
test('lodash.' + methodName + ' can exit early when iterating arrays', function() {
|
||||
var array = [1, 2, 3],
|
||||
values = [];
|
||||
|
||||
@@ -625,7 +559,7 @@
|
||||
deepEqual(values, [1]);
|
||||
});
|
||||
|
||||
test('can exit early when iterating objects', function() {
|
||||
test('lodash.' + methodName + ' can exit early when iterating objects', function() {
|
||||
var object = { 'a': 1, 'b': 2, 'c': 3 },
|
||||
values = [];
|
||||
|
||||
@@ -710,6 +644,15 @@
|
||||
var array = [1, 2, 3];
|
||||
deepEqual(_.initial(array, 0), []);
|
||||
});
|
||||
|
||||
test('should allow a falsey `array` argument', function() {
|
||||
_.each(falsey, function(index, value) {
|
||||
try {
|
||||
var actual = index ? _.initial(value) : _.initial();
|
||||
} catch(e) { }
|
||||
deepEqual(actual, []);
|
||||
})
|
||||
});
|
||||
}());
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
@@ -790,42 +733,33 @@
|
||||
equal(_.isEqual(args1, args3), false);
|
||||
});
|
||||
|
||||
test('should respect custom `isEqual` result despite objects strict equaling each other', function() {
|
||||
var object = { 'isEqual': function() { return false; } };
|
||||
equal(_.isEqual(object, object), false);
|
||||
});
|
||||
|
||||
test('should use custom `isEqual` methods on primitives', function() {
|
||||
Boolean.prototype.isEqual = function() { return true; };
|
||||
equal(_.isEqual(true, false), true);
|
||||
delete Boolean.prototype.isEqual;
|
||||
});
|
||||
|
||||
test('fixes the JScript [[DontEnum]] bug (test in IE < 9)', function() {
|
||||
equal(_.isEqual(shadowed, {}), false);
|
||||
});
|
||||
|
||||
test('should return `true` for like-objects from different documents', function() {
|
||||
if (window.document) {
|
||||
var body = document.body,
|
||||
iframe = document.createElement('iframe'),
|
||||
object = { 'a': 1, 'b': 2, 'c': 3 };
|
||||
|
||||
body.appendChild(iframe);
|
||||
var idoc = (idoc = iframe.contentDocument || iframe.contentWindow).document || idoc;
|
||||
idoc.write("<script>parent._._object = { 'a': 1, 'b': 2, 'c': 3 };<\/script>");
|
||||
idoc.close();
|
||||
}
|
||||
// ensure `_._object` is assigned (unassigned in Opera 10.00)
|
||||
if (_._object) {
|
||||
var object = { 'a': 1, 'b': 2, 'c': 3 };
|
||||
equal(_.isEqual(object, _._object), true);
|
||||
body.removeChild(iframe);
|
||||
delete _._object;
|
||||
}
|
||||
else {
|
||||
skipTest();
|
||||
}
|
||||
});
|
||||
|
||||
test('should return `false` when comparing values with circular references to unlike values', function() {
|
||||
var array1 = ['a', null, 'c'],
|
||||
array2 = ['a', [], 'c'],
|
||||
object1 = { 'a': 1, 'b': null, 'c': 3 },
|
||||
object2 = { 'a': 1, 'b': {}, 'c': 3 };
|
||||
|
||||
array1[1] = array1;
|
||||
equal(_.isEqual(array1, array2), false);
|
||||
|
||||
object1.b = object1;
|
||||
equal(_.isEqual(object1, object2), false);
|
||||
});
|
||||
}());
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
@@ -860,6 +794,24 @@
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
QUnit.module('lodash.isPlainObject');
|
||||
|
||||
(function() {
|
||||
test('should detect plain objects', function() {
|
||||
function Foo(a) {
|
||||
this.a = 1;
|
||||
}
|
||||
|
||||
equal(_.isPlainObject(new Foo(1)), false);
|
||||
equal(_.isPlainObject([1, 2, 3]), false);
|
||||
equal(_.isPlainObject({ 'a': 1 }), true);
|
||||
});
|
||||
}());
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
QUnit.module('isType checks');
|
||||
|
||||
_.each([
|
||||
'isArguments',
|
||||
'isArray',
|
||||
@@ -879,9 +831,8 @@
|
||||
'isUndefined'
|
||||
], function(methodName) {
|
||||
var func = _[methodName];
|
||||
QUnit.module('lodash.' + methodName + ' result');
|
||||
|
||||
test('should return a boolean', function() {
|
||||
test('lodash.' + methodName + ' should return a boolean', function() {
|
||||
var expected = 'boolean';
|
||||
|
||||
equal(typeof func(arguments), expected);
|
||||
@@ -971,6 +922,65 @@
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
QUnit.module('lodash.lateBind');
|
||||
|
||||
(function() {
|
||||
test('should work when the target function is overwritten', function() {
|
||||
var object = {
|
||||
'name': 'moe',
|
||||
'greet': function(greeting) {
|
||||
return greeting + ': ' + this.name;
|
||||
}
|
||||
};
|
||||
|
||||
var func = _.lateBind(object, 'greet', 'hi');
|
||||
equal(func(), 'hi: moe');
|
||||
|
||||
object.greet = function(greeting) {
|
||||
return greeting + ' ' + this.name + '!';
|
||||
};
|
||||
equal(func(), 'hi moe!');
|
||||
});
|
||||
}());
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
QUnit.module('lodash.map');
|
||||
|
||||
(function() {
|
||||
test('should return the correct result when iterating an object', function() {
|
||||
var actual = _.map({ 'a': 1, 'b': 2, 'c': 3 }, function(value) {
|
||||
return value;
|
||||
});
|
||||
deepEqual(actual, [1, 2, 3]);
|
||||
});
|
||||
|
||||
test('should handle object arguments with non-numeric length properties', function() {
|
||||
if (setDescriptor) {
|
||||
var object = {};
|
||||
setDescriptor(object, 'length', { 'value': 'x' });
|
||||
deepEqual(_.map(object, _.identity), []);
|
||||
} else {
|
||||
skipTest();
|
||||
}
|
||||
});
|
||||
}());
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
QUnit.module('lodash.max and lodash.min object iteration');
|
||||
|
||||
_.each(['max', 'min'], function(methodName) {
|
||||
var func = _[methodName];
|
||||
|
||||
test('lodash.' + methodName + ' should iterate an object', function() {
|
||||
var actual = func({ 'a': 1, 'b': 2, 'c': 3 });
|
||||
equal(actual, methodName == 'max' ? 3 : 1);
|
||||
});
|
||||
});
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
QUnit.module('lodash.merge');
|
||||
|
||||
(function() {
|
||||
@@ -1015,7 +1025,6 @@
|
||||
source.bar.b = source.foo.b;
|
||||
|
||||
var actual = _.merge(object, source);
|
||||
|
||||
ok(actual.bar.b === actual.foo.b && actual.foo.b.foo.c === actual.foo.b.foo.c.foo.b.foo.c);
|
||||
});
|
||||
|
||||
@@ -1048,10 +1057,74 @@
|
||||
var actual = _.merge(object, source);
|
||||
equal(_.isArguments(actual.args), false);
|
||||
});
|
||||
|
||||
test('should work with four arguments', function() {
|
||||
var expected = { 'a': 4 };
|
||||
deepEqual(_.merge({ 'a': 1 }, { 'a': 2 }, { 'a': 3 }, expected), expected);
|
||||
});
|
||||
}(1, 2, 3));
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
QUnit.module('lodash.omit');
|
||||
|
||||
(function() {
|
||||
var object = { 'a': 1, 'b': 2 },
|
||||
actual = { 'b': 2 };
|
||||
|
||||
test('should accept individual property names', function() {
|
||||
deepEqual(_.omit(object, 'a'), actual);
|
||||
});
|
||||
|
||||
test('should accept an array of property names', function() {
|
||||
deepEqual(_.omit(object, ['a', 'c']), actual);
|
||||
});
|
||||
|
||||
test('should accept mixes of individual and arrays of property names', function() {
|
||||
deepEqual(_.omit(object, ['a'], 'c'), actual);
|
||||
});
|
||||
|
||||
test('should iterate over inherited properties', function() {
|
||||
function Foo() {}
|
||||
Foo.prototype = object;
|
||||
|
||||
deepEqual(_.omit(new Foo, 'a'), actual);
|
||||
});
|
||||
|
||||
test('should work with a `callback` argument', function() {
|
||||
var actual = _.omit(object, function(value) {
|
||||
return value == 1;
|
||||
});
|
||||
|
||||
deepEqual(actual, { 'b': 2 });
|
||||
});
|
||||
|
||||
test('should pass the correct `callback` arguments', function() {
|
||||
var args,
|
||||
lastKey = _.keys(object).pop();
|
||||
|
||||
var expected = lastKey == 'b'
|
||||
? [1, 'a', object]
|
||||
: [2, 'b', object];
|
||||
|
||||
_.omit(object, function() {
|
||||
args || (args = slice.call(arguments));
|
||||
});
|
||||
|
||||
deepEqual(args, expected);
|
||||
});
|
||||
|
||||
test('should correct set the `this` binding', function() {
|
||||
var actual = _.omit(object, function(value) {
|
||||
return value == this.a;
|
||||
}, { 'a': 1 });
|
||||
|
||||
deepEqual(actual, { 'b': 2 });
|
||||
});
|
||||
}());
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
QUnit.module('lodash.partial');
|
||||
|
||||
(function() {
|
||||
@@ -1151,6 +1224,27 @@
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
QUnit.module('lodash.random');
|
||||
|
||||
(function() {
|
||||
test('should return `0` or `1` when no arguments are passed', function() {
|
||||
var actual = _.random();
|
||||
ok(actual === 0 || actual === 1);
|
||||
});
|
||||
|
||||
test('supports not passing a `max` argument', function() {
|
||||
var actual = _.random(5),
|
||||
start = new Date;
|
||||
|
||||
while ((new Date - start) < 50 && actual == 5) {
|
||||
actual = _.random(5);
|
||||
}
|
||||
ok(actual != 5);
|
||||
});
|
||||
}());
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
QUnit.module('lodash.range');
|
||||
|
||||
(function() {
|
||||
@@ -1218,22 +1312,6 @@
|
||||
deepEqual(args, expected);
|
||||
});
|
||||
|
||||
test('should treat array-like object with invalid `length` as a regular object', function() {
|
||||
var args,
|
||||
object = { 'a': 1, 'length': -1 },
|
||||
lastKey = _.keys(object).pop();
|
||||
|
||||
var expected = lastKey == 'length'
|
||||
? [-1, 1, 'a', object]
|
||||
: [1, -1, 'length', object];
|
||||
|
||||
_.reduceRight(object, function() {
|
||||
args || (args = slice.call(arguments));
|
||||
});
|
||||
|
||||
deepEqual(args, expected);
|
||||
});
|
||||
|
||||
_.each({
|
||||
'literal': 'abc',
|
||||
'object': Object('abc')
|
||||
@@ -1255,6 +1333,32 @@
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
QUnit.module('lodash.rest');
|
||||
|
||||
(function() {
|
||||
test('should allow a falsey `array` argument', function() {
|
||||
_.each(falsey, function(index, value) {
|
||||
try {
|
||||
var actual = index ? _.rest(value) : _.rest();
|
||||
} catch(e) { }
|
||||
deepEqual(actual, []);
|
||||
})
|
||||
});
|
||||
}());
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
QUnit.module('lodash.shuffle');
|
||||
|
||||
(function() {
|
||||
test('should shuffle an object', function() {
|
||||
var actual = _.shuffle({ 'a': 1, 'b': 2, 'c': 3 });
|
||||
deepEqual(actual.sort(), [1, 2, 3]);
|
||||
});
|
||||
}());
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
QUnit.module('lodash.size');
|
||||
|
||||
(function() {
|
||||
@@ -1273,10 +1377,6 @@
|
||||
})
|
||||
});
|
||||
|
||||
test('should work with an object that has a `length` property', function() {
|
||||
equal(_.size({ 'length': 3 }), 1);
|
||||
});
|
||||
|
||||
test('should work with jQuery/MooTools DOM query collections', function() {
|
||||
function Foo(elements) { Array.prototype.push.apply(this, elements); }
|
||||
Foo.prototype = { 'length': 0, 'splice': Array.prototype.splice };
|
||||
@@ -1310,7 +1410,10 @@
|
||||
new Pair(1, 5), new Pair(1, 6),
|
||||
new Pair(2, 1), new Pair(2, 2),
|
||||
new Pair(2, 3), new Pair(2, 4),
|
||||
new Pair(2, 5), new Pair(2, 6)
|
||||
new Pair(2, 5), new Pair(2, 6),
|
||||
new Pair(undefined, 1), new Pair(undefined, 2),
|
||||
new Pair(undefined, 3), new Pair(undefined, 4),
|
||||
new Pair(undefined, 5), new Pair(undefined, 6)
|
||||
];
|
||||
|
||||
var actual = _.sortBy(collection, function(pair) {
|
||||
@@ -1380,13 +1483,13 @@
|
||||
deepEqual(options, {});
|
||||
});
|
||||
|
||||
test('should be debuggable if compiled with errors', function() {
|
||||
var source = _.template('<% if x %>').source;
|
||||
ok(source.indexOf('__p') > -1);
|
||||
});
|
||||
|
||||
test('should raise an error if a template, compiled with errors, is executed', function() {
|
||||
raises(_.template('<% if x %>'));
|
||||
test('should provide the template source when a SyntaxError occurs', function() {
|
||||
try {
|
||||
_.template('<% if x %>');
|
||||
} catch(e) {
|
||||
var source = e.source;
|
||||
}
|
||||
ok((source + '').indexOf('__p') > -1);
|
||||
});
|
||||
|
||||
test('should work with complex "interpolate" delimiters', function() {
|
||||
@@ -1456,6 +1559,23 @@
|
||||
}
|
||||
ok(pass);
|
||||
});
|
||||
|
||||
test('should tokenize delimiters', function() {
|
||||
var compiled = _.template('<span class="icon-<%= type %>2"></span>');
|
||||
equal(compiled({ 'type': 1 }), '<span class="icon-12"></span>');
|
||||
});
|
||||
|
||||
test('should work with "interpolate" delimiters containing ternary operators', function() {
|
||||
var compiled = _.template('<%= value ? value : "b" %>');
|
||||
equal(compiled({ 'value': 'a' }), 'a');
|
||||
});
|
||||
|
||||
test('should parse delimiters with newlines', function() {
|
||||
var expected = '<<\nprint("<p>" + (value ? "yes" : "no") + "</p>")\n>>',
|
||||
compiled = _.template(expected, null, { 'evaluate': /<<(.+?)>>/g });
|
||||
|
||||
equal(compiled({ 'value': true }), expected);
|
||||
});
|
||||
}());
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
@@ -1498,6 +1618,31 @@
|
||||
|
||||
throttled();
|
||||
});
|
||||
|
||||
asyncTest('should clear timeout when `func` is called', function() {
|
||||
var now = new Date,
|
||||
times = [];
|
||||
|
||||
var throttled = _.throttle(function() {
|
||||
times.push(new Date - now);
|
||||
}, 20);
|
||||
|
||||
setTimeout(throttled, 20);
|
||||
setTimeout(throttled, 20);
|
||||
setTimeout(throttled, 40);
|
||||
setTimeout(throttled, 40);
|
||||
|
||||
setTimeout(function() {
|
||||
var actual = _.every(times, function(value, index) {
|
||||
return index
|
||||
? (value - times[index - 1]) > 2
|
||||
: true;
|
||||
});
|
||||
|
||||
ok(actual);
|
||||
QUnit.start();
|
||||
}, 120);
|
||||
});
|
||||
}());
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
@@ -1507,27 +1652,12 @@
|
||||
(function() {
|
||||
var args = arguments;
|
||||
|
||||
_.each({
|
||||
'an array': ['a', 'b', 'c'],
|
||||
'a string': Object('abc')
|
||||
}, function(collection, key) {
|
||||
test('should call custom `toArray` method of ' + key, function() {
|
||||
collection.toArray = function() { return [3, 2, 1]; };
|
||||
deepEqual(_.toArray(collection), [3, 2, 1]);
|
||||
});
|
||||
});
|
||||
|
||||
test('should treat array-like objects like arrays', function() {
|
||||
var object = { '0': 'a', '1': 'b', '2': 'c', 'length': 3 };
|
||||
deepEqual(_.toArray(object), ['a', 'b', 'c']);
|
||||
deepEqual(_.toArray(args), [1, 2, 3]);
|
||||
});
|
||||
|
||||
test('should treat array-like object with invalid `length` as a regular object', function() {
|
||||
var object = { 'length': -1 };
|
||||
deepEqual(_.toArray(object), [-1]);
|
||||
});
|
||||
|
||||
test('should work with a string for `collection` (test in Opera < 10.52)', function() {
|
||||
deepEqual(_.toArray('abc'), ['a', 'b', 'c']);
|
||||
deepEqual(_.toArray(Object('abc')), ['a', 'b', 'c']);
|
||||
@@ -1536,6 +1666,16 @@
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
QUnit.module('lodash.times');
|
||||
|
||||
(function() {
|
||||
test('should return an array of the results of each `callback` execution', function() {
|
||||
deepEqual(_.times(3, function(n) { return n * 2; }), [0, 2, 4]);
|
||||
});
|
||||
}());
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
QUnit.module('lodash.unescape');
|
||||
|
||||
(function() {
|
||||
@@ -1620,15 +1760,9 @@
|
||||
|
||||
deepEqual(_.where(collection, { 'a': 1 }), [{ 'a': 1 }, { 'a': 1, 'b': 2 }]);
|
||||
});
|
||||
}());
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
QUnit.module('lodash.zipObject');
|
||||
|
||||
(function() {
|
||||
test('supports not passing a `values` argument', function() {
|
||||
deepEqual(_.zipObject(['a', 'b', 'c']), { 'a': undefined, 'b': undefined, 'c': undefined });
|
||||
test('should return an empty array when passed an empty `properties` object', function() {
|
||||
deepEqual(_.where(array, {}), []);
|
||||
});
|
||||
}());
|
||||
|
||||
@@ -1666,10 +1800,21 @@
|
||||
|
||||
(function() {
|
||||
test('should allow falsey arguments', function() {
|
||||
var returnArrays = [
|
||||
'filter',
|
||||
'invoke',
|
||||
'map',
|
||||
'pluck',
|
||||
'reject',
|
||||
'shuffle',
|
||||
'sortBy',
|
||||
'toArray',
|
||||
'where'
|
||||
];
|
||||
|
||||
var funcs = _.without.apply(_, [_.functions(_)].concat([
|
||||
'_',
|
||||
'_iteratorTemplate',
|
||||
'_shimKeys',
|
||||
'after',
|
||||
'bind',
|
||||
'bindAll',
|
||||
@@ -1687,18 +1832,77 @@
|
||||
]));
|
||||
|
||||
_.each(funcs, function(methodName) {
|
||||
var func = _[methodName],
|
||||
var actual = [],
|
||||
expected = _.times(falsey.length, function() { return []; }),
|
||||
func = _[methodName],
|
||||
pass = true;
|
||||
|
||||
_.each(falsey, function(value, index) {
|
||||
try {
|
||||
index ? func(value) : func();
|
||||
actual.push(index ? func(value) : func());
|
||||
} catch(e) {
|
||||
pass = false;
|
||||
}
|
||||
});
|
||||
|
||||
ok(pass, methodName + ' allows falsey arguments');
|
||||
if (_.indexOf(returnArrays, methodName) > -1) {
|
||||
deepEqual(actual, expected, '_.' + methodName + ' returns an array');
|
||||
}
|
||||
ok(pass, '_.' + methodName + ' allows falsey arguments');
|
||||
});
|
||||
});
|
||||
|
||||
test('should handle `null` `thisArg` arguments', function() {
|
||||
var thisArg,
|
||||
array = ['a'],
|
||||
callback = function() { thisArg = this; },
|
||||
expected = (function() { return this; }).call(null);
|
||||
|
||||
var funcs = [
|
||||
'countBy',
|
||||
'every',
|
||||
'filter',
|
||||
'find',
|
||||
'forEach',
|
||||
'forIn',
|
||||
'forOwn',
|
||||
'groupBy',
|
||||
'map',
|
||||
'max',
|
||||
'min',
|
||||
'omit',
|
||||
'pick',
|
||||
'reduce',
|
||||
'reduceRight',
|
||||
'reject',
|
||||
'some',
|
||||
'sortBy',
|
||||
'sortedIndex',
|
||||
'times',
|
||||
'uniq'
|
||||
];
|
||||
|
||||
_.each(funcs, function(methodName) {
|
||||
var func = _[methodName],
|
||||
message = '_.' + methodName + ' handles `null` `thisArg` arguments';
|
||||
|
||||
thisArg = undefined;
|
||||
|
||||
if (/^reduce/.test(methodName)) {
|
||||
func(array, callback, 0, null);
|
||||
} else if (methodName == 'sortedIndex') {
|
||||
func(array, 'a', callback, null);
|
||||
} else if (methodName == 'times') {
|
||||
func(1, callback, null);
|
||||
} else {
|
||||
func(array, callback, null);
|
||||
}
|
||||
|
||||
if (expected === null) {
|
||||
deepEqual(thisArg, null, message);
|
||||
} else {
|
||||
equal(thisArg, expected, message);
|
||||
}
|
||||
});
|
||||
});
|
||||
}());
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Underscore Test Suite</title>
|
||||
<link rel="stylesheet" href="../vendor/underscore/test/vendor/qunit.css">
|
||||
<link rel="stylesheet" href="../vendor/qunit/qunit/qunit.css">
|
||||
<style>
|
||||
#jslitmus, iframe {
|
||||
iframe, img {
|
||||
display: none;
|
||||
}
|
||||
</style>
|
||||
@@ -17,14 +17,21 @@
|
||||
<div id="id1"></div>
|
||||
<div id="id2"></div>
|
||||
</div>
|
||||
<img id="chart_image" src="data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==">
|
||||
</div>
|
||||
<script src="../vendor/backbone/test/vendor/json2.js"></script>
|
||||
<script src="../vendor/underscore/test/vendor/jquery.js"></script>
|
||||
<script src="../vendor/underscore/test/vendor/qunit.js"></script>
|
||||
<script src="../vendor/underscore/test/vendor/jslitmus.js"></script>
|
||||
<script src="../vendor/json3/lib/json3.js"></script>
|
||||
<script src="../vendor/jquery/jquery.js"></script>
|
||||
<script src="../vendor/platform.js/platform.js"></script>
|
||||
<script>
|
||||
// avoid syntax errors for `QUnit.throws` in older Firefoxes
|
||||
document.write(platform.name == 'Firefox' && /^1\b/.test(platform.version)
|
||||
? '<script src="../vendor/qunit/qunit/qunit-1.8.0.js"><\/script>'
|
||||
: '<script src="../vendor/qunit/qunit/qunit.js"><\/script>'
|
||||
);
|
||||
</script>
|
||||
<script src="test-ui.js"></script>
|
||||
<script>
|
||||
document.write('<script src="../' + QUnit.config.lodashFilename + '.js"><\/script>');
|
||||
document.write('<script src="../' + ui.buildPath + '"><\/script>');
|
||||
</script>
|
||||
<script src="../vendor/underscore/test/collections.js"></script>
|
||||
<script src="../vendor/underscore/test/arrays.js"></script>
|
||||
|
||||
424
vendor/backbone/backbone.js
vendored
424
vendor/backbone/backbone.js
vendored
@@ -10,7 +10,7 @@
|
||||
// Initial Setup
|
||||
// -------------
|
||||
|
||||
// Save a reference to the global object (`window` in the browser, `global`
|
||||
// Save a reference to the global object (`window` in the browser, `exports`
|
||||
// on the server).
|
||||
var root = this;
|
||||
|
||||
@@ -18,8 +18,11 @@
|
||||
// restored later on, if `noConflict` is used.
|
||||
var previousBackbone = root.Backbone;
|
||||
|
||||
// Create a local reference to splice.
|
||||
var splice = Array.prototype.splice;
|
||||
// Create a local reference to array methods.
|
||||
var ArrayProto = Array.prototype;
|
||||
var push = ArrayProto.push;
|
||||
var slice = ArrayProto.slice;
|
||||
var splice = ArrayProto.splice;
|
||||
|
||||
// The top-level namespace. All public Backbone classes and modules will
|
||||
// be attached to this. Exported for both CommonJS and the browser.
|
||||
@@ -59,7 +62,7 @@
|
||||
Backbone.emulateJSON = false;
|
||||
|
||||
// Backbone.Events
|
||||
// -----------------
|
||||
// ---------------
|
||||
|
||||
// Regular expression used to split event strings
|
||||
var eventSplitter = /\s+/;
|
||||
@@ -180,22 +183,22 @@
|
||||
// is automatically generated and assigned for you.
|
||||
var Model = Backbone.Model = function(attributes, options) {
|
||||
var defaults;
|
||||
attributes || (attributes = {});
|
||||
var attrs = attributes || {};
|
||||
if (options && options.collection) this.collection = options.collection;
|
||||
if (options && options.parse) attributes = this.parse(attributes);
|
||||
if (defaults = getValue(this, 'defaults')) {
|
||||
attributes = _.extend({}, defaults, attributes);
|
||||
if (options && options.parse) attrs = this.parse(attrs);
|
||||
if (defaults = _.result(this, 'defaults')) {
|
||||
attrs = _.extend({}, defaults, attrs);
|
||||
}
|
||||
this.attributes = {};
|
||||
this._escapedAttributes = {};
|
||||
this.cid = _.uniqueId('c');
|
||||
this.changed = {};
|
||||
this._silent = {};
|
||||
this._changes = {};
|
||||
this._pending = {};
|
||||
this.set(attributes, {silent: true});
|
||||
this.set(attrs, {silent: true});
|
||||
// Reset change tracking.
|
||||
this.changed = {};
|
||||
this._silent = {};
|
||||
this._changes = {};
|
||||
this._pending = {};
|
||||
this._previousAttributes = _.clone(this.attributes);
|
||||
this.initialize.apply(this, arguments);
|
||||
@@ -207,14 +210,18 @@
|
||||
// A hash of attributes whose current and previous value differ.
|
||||
changed: null,
|
||||
|
||||
// A hash of attributes that have silently changed since the last time
|
||||
// `change` was called. Will become pending attributes on the next call.
|
||||
_silent: null,
|
||||
// A hash of attributes that have changed since the last time `change`
|
||||
// was called.
|
||||
_changes: null,
|
||||
|
||||
// A hash of attributes that have changed since the last `'change'` event
|
||||
// A hash of attributes that have changed since the last `change` event
|
||||
// began.
|
||||
_pending: null,
|
||||
|
||||
// A hash of attributes with the current model state to determine if
|
||||
// a `change` should be recorded within a nested `change` block.
|
||||
_changing : null,
|
||||
|
||||
// The default name for the JSON `id` attribute is `"id"`. MongoDB and
|
||||
// CouchDB users may want to set this to `"_id"`.
|
||||
idAttribute: 'id',
|
||||
@@ -254,23 +261,22 @@
|
||||
|
||||
// Set a hash of model attributes on the object, firing `"change"` unless
|
||||
// you choose to silence it.
|
||||
set: function(key, value, options) {
|
||||
var attrs, attr, val;
|
||||
set: function(attrs, options) {
|
||||
var attr, key, val;
|
||||
if (attrs == null) return this;
|
||||
|
||||
// Handle both `"key", value` and `{key: value}` -style arguments.
|
||||
if (_.isObject(key) || key == null) {
|
||||
attrs = key;
|
||||
options = value;
|
||||
} else {
|
||||
attrs = {};
|
||||
attrs[key] = value;
|
||||
if (!_.isObject(attrs)) {
|
||||
key = attrs;
|
||||
(attrs = {})[key] = options;
|
||||
options = arguments[2];
|
||||
}
|
||||
|
||||
// Extract attributes and options.
|
||||
options || (options = {});
|
||||
if (!attrs) return this;
|
||||
var silent = options && options.silent;
|
||||
var unset = options && options.unset;
|
||||
if (attrs instanceof Model) attrs = attrs.attributes;
|
||||
if (options.unset) for (attr in attrs) attrs[attr] = void 0;
|
||||
if (unset) for (attr in attrs) attrs[attr] = void 0;
|
||||
|
||||
// Run validation.
|
||||
if (!this._validate(attrs, options)) return false;
|
||||
@@ -278,7 +284,7 @@
|
||||
// Check for changes of `id`.
|
||||
if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
|
||||
|
||||
var changes = options.changes = {};
|
||||
var changing = this._changing;
|
||||
var now = this.attributes;
|
||||
var escaped = this._escapedAttributes;
|
||||
var prev = this._previousAttributes || {};
|
||||
@@ -288,27 +294,30 @@
|
||||
val = attrs[attr];
|
||||
|
||||
// If the new and current value differ, record the change.
|
||||
if (!_.isEqual(now[attr], val) || (options.unset && _.has(now, attr))) {
|
||||
if (!_.isEqual(now[attr], val) || (unset && _.has(now, attr))) {
|
||||
delete escaped[attr];
|
||||
(options.silent ? this._silent : changes)[attr] = true;
|
||||
this._changes[attr] = true;
|
||||
}
|
||||
|
||||
// Update or delete the current value.
|
||||
options.unset ? delete now[attr] : now[attr] = val;
|
||||
unset ? delete now[attr] : now[attr] = val;
|
||||
|
||||
// If the new and previous value differ, record the change. If not,
|
||||
// then remove changes for this attribute.
|
||||
if (!_.isEqual(prev[attr], val) || (_.has(now, attr) !== _.has(prev, attr))) {
|
||||
this.changed[attr] = val;
|
||||
if (!options.silent) this._pending[attr] = true;
|
||||
if (!silent) this._pending[attr] = true;
|
||||
} else {
|
||||
delete this.changed[attr];
|
||||
delete this._pending[attr];
|
||||
if (!changing) delete this._changes[attr];
|
||||
}
|
||||
|
||||
if (changing && _.isEqual(now[attr], changing[attr])) delete this._changes[attr];
|
||||
}
|
||||
|
||||
// Fire the `"change"` events.
|
||||
if (!options.silent) this.change(options);
|
||||
if (!silent) this.change(options);
|
||||
return this;
|
||||
},
|
||||
|
||||
@@ -336,25 +345,21 @@
|
||||
options.success = function(resp, status, xhr) {
|
||||
if (!model.set(model.parse(resp, xhr), options)) return false;
|
||||
if (success) success(model, resp, options);
|
||||
model.trigger('sync', model, resp, options);
|
||||
};
|
||||
options.error = Backbone.wrapError(options.error, model, options);
|
||||
return this.sync('read', this, options);
|
||||
},
|
||||
|
||||
// Set a hash of model attributes, and sync the model to the server.
|
||||
// If the server returns an attributes hash that differs, the model's
|
||||
// state will be `set` again.
|
||||
save: function(key, value, options) {
|
||||
var attrs, current, done;
|
||||
save: function(attrs, options) {
|
||||
var key, current, done;
|
||||
|
||||
// Handle both `("key", value)` and `({key: value})` -style calls.
|
||||
if (_.isObject(key) || key == null) {
|
||||
attrs = key;
|
||||
options = value;
|
||||
} else {
|
||||
attrs = {};
|
||||
attrs[key] = value;
|
||||
// Handle both `"key", value` and `{key: value}` -style arguments.
|
||||
if (attrs != null && !_.isObject(attrs)) {
|
||||
key = attrs;
|
||||
(attrs = {})[key] = options;
|
||||
options = arguments[2];
|
||||
}
|
||||
options = options ? _.clone(options) : {};
|
||||
|
||||
@@ -371,7 +376,7 @@
|
||||
}
|
||||
|
||||
// Do not persist invalid models.
|
||||
if (!attrs && !this.isValid()) return false;
|
||||
if (!attrs && !this._validate(null, options)) return false;
|
||||
|
||||
// After a successful server-side save, the client is (optionally)
|
||||
// updated with the server-side state.
|
||||
@@ -383,11 +388,9 @@
|
||||
if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
|
||||
if (!model.set(serverAttrs, options)) return false;
|
||||
if (success) success(model, resp, options);
|
||||
model.trigger('sync', model, resp, options);
|
||||
};
|
||||
|
||||
// Finish configuring and sending the Ajax request.
|
||||
options.error = Backbone.wrapError(options.error, model, options);
|
||||
var xhr = this.sync(this.isNew() ? 'create' : 'update', this, options);
|
||||
|
||||
// When using `wait`, reset attributes to original values unless
|
||||
@@ -415,7 +418,6 @@
|
||||
options.success = function(resp) {
|
||||
if (options.wait || model.isNew()) destroy();
|
||||
if (success) success(model, resp, options);
|
||||
if (!model.isNew()) model.trigger('sync', model, resp, options);
|
||||
};
|
||||
|
||||
if (this.isNew()) {
|
||||
@@ -423,7 +425,6 @@
|
||||
return false;
|
||||
}
|
||||
|
||||
options.error = Backbone.wrapError(options.error, model, options);
|
||||
var xhr = this.sync('delete', this, options);
|
||||
if (!options.wait) destroy();
|
||||
return xhr;
|
||||
@@ -433,7 +434,7 @@
|
||||
// using Backbone's restful methods, override this to change the endpoint
|
||||
// that will be called.
|
||||
url: function() {
|
||||
var base = getValue(this, 'urlRoot') || getValue(this.collection, 'url') || urlError();
|
||||
var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError();
|
||||
if (this.isNew()) return base;
|
||||
return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.id);
|
||||
},
|
||||
@@ -458,18 +459,25 @@
|
||||
// a `"change:attribute"` event for each changed attribute.
|
||||
// Calling this will cause all objects observing the model to update.
|
||||
change: function(options) {
|
||||
options || (options = {});
|
||||
var changing = this._changing;
|
||||
this._changing = true;
|
||||
var current = this._changing = {};
|
||||
|
||||
// Silent changes become pending changes.
|
||||
for (var attr in this._silent) this._pending[attr] = true;
|
||||
for (var attr in this._changes) this._pending[attr] = true;
|
||||
|
||||
// Silent changes are triggered.
|
||||
var changes = _.extend({}, options.changes, this._silent);
|
||||
this._silent = {};
|
||||
// Trigger 'change:attr' for any new or silent changes.
|
||||
var changes = this._changes;
|
||||
this._changes = {};
|
||||
|
||||
// Set the correct state for this._changing values
|
||||
var triggers = [];
|
||||
for (var attr in changes) {
|
||||
this.trigger('change:' + attr, this, this.get(attr), options);
|
||||
current[attr] = this.get(attr);
|
||||
triggers.push(attr);
|
||||
}
|
||||
|
||||
for (var i=0, l=triggers.length; i < l; i++) {
|
||||
this.trigger('change:' + triggers[i], this, current[triggers[i]], options);
|
||||
}
|
||||
if (changing) return this;
|
||||
|
||||
@@ -479,13 +487,13 @@
|
||||
this.trigger('change', this, options);
|
||||
// Pending and silent changes still remain.
|
||||
for (var attr in this.changed) {
|
||||
if (this._pending[attr] || this._silent[attr]) continue;
|
||||
if (this._pending[attr] || this._changes[attr]) continue;
|
||||
delete this.changed[attr];
|
||||
}
|
||||
this._previousAttributes = _.clone(this.attributes);
|
||||
}
|
||||
|
||||
this._changing = false;
|
||||
this._changing = null;
|
||||
return this;
|
||||
},
|
||||
|
||||
@@ -527,23 +535,20 @@
|
||||
|
||||
// Check if the model is currently in a valid state. It's only possible to
|
||||
// get into an *invalid* state if you're using silent changes.
|
||||
isValid: function() {
|
||||
return !this.validate || !this.validate(this.attributes);
|
||||
isValid: function(options) {
|
||||
return !this.validate || !this.validate(this.attributes, options);
|
||||
},
|
||||
|
||||
// Run validation against the next complete set of model attributes,
|
||||
// returning `true` if all is well. If a specific `error` callback has
|
||||
// been passed, call that instead of firing the general `"error"` event.
|
||||
_validate: function(attrs, options) {
|
||||
if (options.silent || !this.validate) return true;
|
||||
if (options && options.silent || !this.validate) return true;
|
||||
attrs = _.extend({}, this.attributes, attrs);
|
||||
var error = this.validate(attrs, options);
|
||||
if (!error) return true;
|
||||
if (options && options.error) {
|
||||
options.error(this, error, options);
|
||||
} else {
|
||||
this.trigger('error', this, error, options);
|
||||
}
|
||||
if (options && options.error) options.error(this, error, options);
|
||||
this.trigger('error', this, error, options);
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -592,59 +597,51 @@
|
||||
// Add a model, or list of models to the set. Pass **silent** to avoid
|
||||
// firing the `add` event for every new model.
|
||||
add: function(models, options) {
|
||||
var i, index, length, model, cid, id, cids = {}, ids = {}, dups = [];
|
||||
options || (options = {});
|
||||
var i, args, length, model, existing;
|
||||
var at = options && options.at;
|
||||
models = _.isArray(models) ? models.slice() : [models];
|
||||
|
||||
// Begin by turning bare objects into model references, and preventing
|
||||
// invalid models or duplicate models from being added.
|
||||
// invalid models from being added.
|
||||
for (i = 0, length = models.length; i < length; i++) {
|
||||
if (!(model = models[i] = this._prepareModel(models[i], options))) {
|
||||
throw new Error("Can't add an invalid model to a collection");
|
||||
}
|
||||
cid = model.cid;
|
||||
id = model.id;
|
||||
if (cids[cid] || this._byCid[cid] || ((id != null) && (ids[id] || this._byId[id]))) {
|
||||
dups.push(i);
|
||||
if (models[i] = this._prepareModel(models[i], options)) continue;
|
||||
throw new Error("Can't add an invalid model to a collection");
|
||||
}
|
||||
|
||||
for (i = models.length - 1; i >= 0; i--) {
|
||||
model = models[i];
|
||||
existing = model.id != null && this._byId[model.id];
|
||||
|
||||
// If a duplicate is found, splice it out and optionally merge it into
|
||||
// the existing model.
|
||||
if (existing || this._byCid[model.cid]) {
|
||||
if (options && options.merge && existing) {
|
||||
existing.set(model, options);
|
||||
}
|
||||
models.splice(i, 1);
|
||||
continue;
|
||||
}
|
||||
cids[cid] = ids[id] = model;
|
||||
}
|
||||
|
||||
// Remove duplicates.
|
||||
i = dups.length;
|
||||
while (i--) {
|
||||
dups[i] = models.splice(dups[i], 1)[0];
|
||||
}
|
||||
|
||||
// Listen to added models' events, and index models for lookup by
|
||||
// `id` and by `cid`.
|
||||
for (i = 0, length = models.length; i < length; i++) {
|
||||
(model = models[i]).on('all', this._onModelEvent, this);
|
||||
// Listen to added models' events, and index models for lookup by
|
||||
// `id` and by `cid`.
|
||||
model.on('all', this._onModelEvent, this);
|
||||
this._byCid[model.cid] = model;
|
||||
if (model.id != null) this._byId[model.id] = model;
|
||||
}
|
||||
|
||||
// Insert models into the collection, re-sorting if needed, and triggering
|
||||
// `add` events unless silenced.
|
||||
this.length += length;
|
||||
index = options.at != null ? options.at : this.models.length;
|
||||
splice.apply(this.models, [index, 0].concat(models));
|
||||
|
||||
// Merge in duplicate models.
|
||||
if (options.merge) {
|
||||
for (i = 0, length = dups.length; i < length; i++) {
|
||||
if (model = this._byId[dups[i].id]) model.set(dups[i], options);
|
||||
}
|
||||
}
|
||||
// Update `length` and splice in new models.
|
||||
this.length += models.length;
|
||||
args = [at != null ? at : this.models.length, 0];
|
||||
push.apply(args, models);
|
||||
splice.apply(this.models, args);
|
||||
|
||||
// Sort the collection if appropriate.
|
||||
if (this.comparator && options.at == null) this.sort({silent: true});
|
||||
if (this.comparator && at == null) this.sort({silent: true});
|
||||
|
||||
if (options.silent) return this;
|
||||
for (i = 0, length = this.models.length; i < length; i++) {
|
||||
if (!cids[(model = this.models[i]).cid]) continue;
|
||||
options.index = i;
|
||||
if (options && options.silent) return this;
|
||||
|
||||
// Trigger `add` events.
|
||||
while (model = models.shift()) {
|
||||
model.trigger('add', model, this, options);
|
||||
}
|
||||
|
||||
@@ -738,35 +735,35 @@
|
||||
// normal circumstances, as the set will maintain sort order as each item
|
||||
// is added.
|
||||
sort: function(options) {
|
||||
options || (options = {});
|
||||
if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
|
||||
var boundComparator = _.bind(this.comparator, this);
|
||||
if (this.comparator.length === 1) {
|
||||
this.models = this.sortBy(boundComparator);
|
||||
} else {
|
||||
this.models.sort(boundComparator);
|
||||
if (!this.comparator) {
|
||||
throw new Error('Cannot sort a set without a comparator');
|
||||
}
|
||||
if (!options.silent) this.trigger('reset', this, options);
|
||||
|
||||
if (_.isString(this.comparator) || this.comparator.length === 1) {
|
||||
this.models = this.sortBy(this.comparator, this);
|
||||
} else {
|
||||
this.models.sort(_.bind(this.comparator, this));
|
||||
}
|
||||
|
||||
if (!options || !options.silent) this.trigger('reset', this, options);
|
||||
return this;
|
||||
},
|
||||
|
||||
// Pluck an attribute from each model in the collection.
|
||||
pluck: function(attr) {
|
||||
return _.map(this.models, function(model){ return model.get(attr); });
|
||||
return _.invoke(this.models, 'get', attr);
|
||||
},
|
||||
|
||||
// When you have more items than you want to add or remove individually,
|
||||
// you can reset the entire set with a new list of models, without firing
|
||||
// any `add` or `remove` events. Fires `reset` when finished.
|
||||
reset: function(models, options) {
|
||||
models || (models = []);
|
||||
options || (options = {});
|
||||
for (var i = 0, l = this.models.length; i < l; i++) {
|
||||
this._removeReference(this.models[i]);
|
||||
}
|
||||
this._reset();
|
||||
this.add(models, _.extend({silent: true}, options));
|
||||
if (!options.silent) this.trigger('reset', this, options);
|
||||
if (models) this.add(models, _.extend({silent: true}, options));
|
||||
if (!options || !options.silent) this.trigger('reset', this, options);
|
||||
return this;
|
||||
},
|
||||
|
||||
@@ -781,9 +778,7 @@
|
||||
options.success = function(resp, status, xhr) {
|
||||
collection[options.add ? 'add' : 'reset'](collection.parse(resp, xhr), options);
|
||||
if (success) success(collection, resp, options);
|
||||
collection.trigger('sync', collection, resp, options);
|
||||
};
|
||||
options.error = Backbone.wrapError(options.error, collection, options);
|
||||
return this.sync('read', this, options);
|
||||
},
|
||||
|
||||
@@ -870,19 +865,34 @@
|
||||
var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl',
|
||||
'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select',
|
||||
'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke',
|
||||
'max', 'min', 'sortBy', 'sortedIndex', 'toArray', 'size', 'first', 'head',
|
||||
'take', 'initial', 'rest', 'tail', 'last', 'without', 'indexOf', 'shuffle',
|
||||
'lastIndexOf', 'isEmpty', 'groupBy'];
|
||||
'max', 'min', 'sortedIndex', 'toArray', 'size', 'first', 'head', 'take',
|
||||
'initial', 'rest', 'tail', 'last', 'without', 'indexOf', 'shuffle',
|
||||
'lastIndexOf', 'isEmpty'];
|
||||
|
||||
// Mix in each Underscore method as a proxy to `Collection#models`.
|
||||
_.each(methods, function(method) {
|
||||
Collection.prototype[method] = function() {
|
||||
return _[method].apply(_, [this.models].concat(_.toArray(arguments)));
|
||||
var args = slice.call(arguments);
|
||||
args.unshift(this.models);
|
||||
return _[method].apply(_, args);
|
||||
};
|
||||
});
|
||||
|
||||
// Underscore methods that take a property name as an argument.
|
||||
var attributeMethods = ['groupBy', 'countBy', 'sortBy'];
|
||||
|
||||
// Use attributes instead of properties.
|
||||
_.each(attributeMethods, function(method) {
|
||||
Collection.prototype[method] = function(value, context) {
|
||||
var iterator = _.isFunction(value) ? value : function(model) {
|
||||
return model.get(value);
|
||||
};
|
||||
return _[method](this.models, iterator, context);
|
||||
};
|
||||
});
|
||||
|
||||
// Backbone.Router
|
||||
// -------------------
|
||||
// ---------------
|
||||
|
||||
// Routers map faux-URLs to actions, and fire events when routes are
|
||||
// matched. Creating a new one sets its `routes` hash, if not set statically.
|
||||
@@ -895,9 +905,10 @@
|
||||
|
||||
// Cached regular expressions for matching named param parts and splatted
|
||||
// parts of route strings.
|
||||
var optionalParam = /\((.*?)\)/g;
|
||||
var namedParam = /:\w+/g;
|
||||
var splatParam = /\*\w+/g;
|
||||
var escapeRegExp = /[-[\]{}()+?.,\\^$|#\s]/g;
|
||||
var escapeRegExp = /[-{}[\]+?.,\\^$|#\s]/g;
|
||||
|
||||
// Set up all inheritable **Backbone.Router** properties and methods.
|
||||
_.extend(Router.prototype, Events, {
|
||||
@@ -913,7 +924,6 @@
|
||||
// });
|
||||
//
|
||||
route: function(route, name, callback) {
|
||||
Backbone.history || (Backbone.history = new History);
|
||||
if (!_.isRegExp(route)) route = this._routeToRegExp(route);
|
||||
if (!callback) callback = this[name];
|
||||
Backbone.history.route(route, _.bind(function(fragment) {
|
||||
@@ -928,6 +938,7 @@
|
||||
// Simple proxy to `Backbone.history` to save a fragment into the history.
|
||||
navigate: function(fragment, options) {
|
||||
Backbone.history.navigate(fragment, options);
|
||||
return this;
|
||||
},
|
||||
|
||||
// Bind all defined routes to `Backbone.history`. We have to reverse the
|
||||
@@ -935,12 +946,10 @@
|
||||
// routes can be defined at the bottom of the route map.
|
||||
_bindRoutes: function() {
|
||||
if (!this.routes) return;
|
||||
var routes = [];
|
||||
for (var route in this.routes) {
|
||||
routes.unshift([route, this.routes[route]]);
|
||||
}
|
||||
for (var i = 0, l = routes.length; i < l; i++) {
|
||||
this.route(routes[i][0], routes[i][1], this[routes[i][1]]);
|
||||
var route, routes = _.keys(this.routes);
|
||||
while ((route = routes.pop()) != null) {
|
||||
var name = this.routes[route];
|
||||
this.route(route, name, this[name]);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -948,6 +957,7 @@
|
||||
// against the current location hash.
|
||||
_routeToRegExp: function(route) {
|
||||
route = route.replace(escapeRegExp, '\\$&')
|
||||
.replace(optionalParam, '(?:$1)?')
|
||||
.replace(namedParam, '([^\/]+)')
|
||||
.replace(splatParam, '(.*?)');
|
||||
return new RegExp('^' + route + '$');
|
||||
@@ -966,16 +976,23 @@
|
||||
|
||||
// Handles cross-browser history management, based on URL fragments. If the
|
||||
// browser does not support `onhashchange`, falls back to polling.
|
||||
var History = Backbone.History = function(options) {
|
||||
var History = Backbone.History = function() {
|
||||
this.handlers = [];
|
||||
_.bindAll(this, 'checkUrl');
|
||||
this.location = options && options.location || root.location;
|
||||
this.history = options && options.history || root.history;
|
||||
|
||||
// #1653 - Ensure that `History` can be used outside of the browser.
|
||||
if (typeof window !== 'undefined') {
|
||||
this.location = window.location;
|
||||
this.history = window.history;
|
||||
}
|
||||
};
|
||||
|
||||
// Cached regex for cleaning leading hashes and slashes .
|
||||
// Cached regex for cleaning leading hashes and slashes.
|
||||
var routeStripper = /^[#\/]/;
|
||||
|
||||
// Cached regex for stripping leading and trailing slashes.
|
||||
var rootStripper = /^\/+|\/+$/g;
|
||||
|
||||
// Cached regex for detecting MSIE.
|
||||
var isExplorer = /msie [\w.]+/;
|
||||
|
||||
@@ -1005,7 +1022,7 @@
|
||||
if (fragment == null) {
|
||||
if (this._hasPushState || !this._wantsHashChange || forcePushState) {
|
||||
fragment = this.location.pathname;
|
||||
var root = this.options.root.replace(trailingSlash, '');
|
||||
var root = this.root.replace(trailingSlash, '');
|
||||
if (!fragment.indexOf(root)) fragment = fragment.substr(root.length);
|
||||
} else {
|
||||
fragment = this.getHash();
|
||||
@@ -1023,6 +1040,7 @@
|
||||
// Figure out the initial configuration. Do we need an iframe?
|
||||
// Is pushState desired ... is it available?
|
||||
this.options = _.extend({}, {root: '/'}, this.options, options);
|
||||
this.root = this.options.root;
|
||||
this._wantsHashChange = this.options.hashChange !== false;
|
||||
this._wantsPushState = !!this.options.pushState;
|
||||
this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState);
|
||||
@@ -1030,8 +1048,8 @@
|
||||
var docMode = document.documentMode;
|
||||
var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));
|
||||
|
||||
// Normalize root to always include trailing slash
|
||||
if (!trailingSlash.test(this.options.root)) this.options.root += '/';
|
||||
// Normalize root to always include a leading and trailing slash.
|
||||
this.root = ('/' + this.root + '/').replace(rootStripper, '/');
|
||||
|
||||
if (oldIE && this._wantsHashChange) {
|
||||
this.iframe = Backbone.$('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow;
|
||||
@@ -1052,13 +1070,13 @@
|
||||
// opened by a non-pushState browser.
|
||||
this.fragment = fragment;
|
||||
var loc = this.location;
|
||||
var atRoot = (loc.pathname.replace(/[^/]$/, '$&/') === this.options.root) && !loc.search;
|
||||
var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root;
|
||||
|
||||
// If we've started off with a route from a `pushState`-enabled browser,
|
||||
// but we're currently in a browser that doesn't support it...
|
||||
if (this._wantsHashChange && this._wantsPushState && !this._hasPushState && !atRoot) {
|
||||
this.fragment = this.getFragment(null, true);
|
||||
this.location.replace(this.options.root + this.location.search + '#' + this.fragment);
|
||||
this.location.replace(this.root + this.location.search + '#' + this.fragment);
|
||||
// Return immediately as browser will do redirect to new url
|
||||
return true;
|
||||
|
||||
@@ -1066,7 +1084,7 @@
|
||||
// in a browser where it could be `pushState`-based instead...
|
||||
} else if (this._wantsPushState && this._hasPushState && atRoot && loc.hash) {
|
||||
this.fragment = this.getHash().replace(routeStripper, '');
|
||||
this.history.replaceState({}, document.title, loc.protocol + '//' + loc.host + this.options.root + this.fragment);
|
||||
this.history.replaceState({}, document.title, this.root + this.fragment + loc.search);
|
||||
}
|
||||
|
||||
if (!this.options.silent) return this.loadUrl();
|
||||
@@ -1122,10 +1140,10 @@
|
||||
navigate: function(fragment, options) {
|
||||
if (!History.started) return false;
|
||||
if (!options || options === true) options = {trigger: options};
|
||||
var frag = (fragment || '').replace(routeStripper, '');
|
||||
if (this.fragment === frag) return;
|
||||
this.fragment = frag;
|
||||
var url = (frag.indexOf(this.options.root) !== 0 ? this.options.root : '') + frag;
|
||||
fragment = this.getFragment(fragment || '');
|
||||
if (this.fragment === fragment) return;
|
||||
this.fragment = fragment;
|
||||
var url = this.root + fragment;
|
||||
|
||||
// If pushState is available, we use it to set the fragment as a real URL.
|
||||
if (this._hasPushState) {
|
||||
@@ -1134,13 +1152,13 @@
|
||||
// If hash changes haven't been explicitly disabled, update the hash
|
||||
// fragment to store history.
|
||||
} else if (this._wantsHashChange) {
|
||||
this._updateHash(this.location, frag, options.replace);
|
||||
if (this.iframe && (frag !== this.getFragment(this.getHash(this.iframe)))) {
|
||||
this._updateHash(this.location, fragment, options.replace);
|
||||
if (this.iframe && (fragment !== this.getFragment(this.getHash(this.iframe)))) {
|
||||
// Opening and closing the iframe tricks IE7 and earlier to push a
|
||||
// history entry on hash-tag change. When replace is true, we don't
|
||||
// want this.
|
||||
if(!options.replace) this.iframe.document.open().close();
|
||||
this._updateHash(this.iframe.location, frag, options.replace);
|
||||
this._updateHash(this.iframe.location, fragment, options.replace);
|
||||
}
|
||||
|
||||
// If you've told us that you explicitly don't want fallback hashchange-
|
||||
@@ -1155,14 +1173,19 @@
|
||||
// a new one to the browser history.
|
||||
_updateHash: function(location, fragment, replace) {
|
||||
if (replace) {
|
||||
location.replace(location.href.replace(/(javascript:|#).*$/, '') + '#' + fragment);
|
||||
var href = location.href.replace(/(javascript:|#).*$/, '');
|
||||
location.replace(href + '#' + fragment);
|
||||
} else {
|
||||
location.hash = fragment;
|
||||
// #1649 - Some browsers require that `hash` contains a leading #.
|
||||
location.hash = '#' + fragment;
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
// Create the default Backbone.history.
|
||||
Backbone.history = new History;
|
||||
|
||||
// Backbone.View
|
||||
// -------------
|
||||
|
||||
@@ -1209,8 +1232,8 @@
|
||||
// memory leaks.
|
||||
dispose: function() {
|
||||
this.undelegateEvents();
|
||||
if (this.model) this.model.off(null, null, this);
|
||||
if (this.collection) this.collection.off(null, null, this);
|
||||
if (this.model && this.model.off) this.model.off(null, null, this);
|
||||
if (this.collection && this.collection.off) this.collection.off(null, null, this);
|
||||
return this;
|
||||
},
|
||||
|
||||
@@ -1260,7 +1283,7 @@
|
||||
// This only works for delegate-able events: not `focus`, `blur`, and
|
||||
// not `change`, `submit`, and `reset` in Internet Explorer.
|
||||
delegateEvents: function(events) {
|
||||
if (!(events || (events = getValue(this, 'events')))) return;
|
||||
if (!(events || (events = _.result(this, 'events')))) return;
|
||||
this.undelegateEvents();
|
||||
for (var key in events) {
|
||||
var method = events[key];
|
||||
@@ -1290,10 +1313,7 @@
|
||||
// attached directly to the view.
|
||||
_configure: function(options) {
|
||||
if (this.options) options = _.extend({}, this.options, options);
|
||||
for (var i = 0, l = viewOptions.length; i < l; i++) {
|
||||
var attr = viewOptions[i];
|
||||
if (options[attr]) this[attr] = options[attr];
|
||||
}
|
||||
_.extend(this, _.pick(options, viewOptions));
|
||||
this.options = options;
|
||||
},
|
||||
|
||||
@@ -1303,12 +1323,12 @@
|
||||
// an element from the `id`, `className` and `tagName` properties.
|
||||
_ensureElement: function() {
|
||||
if (!this.el) {
|
||||
var attrs = _.extend({}, getValue(this, 'attributes'));
|
||||
if (this.id) attrs.id = getValue(this, 'id');
|
||||
if (this.className) attrs['class'] = getValue(this, 'className');
|
||||
this.setElement(this.make(getValue(this, 'tagName'), attrs), false);
|
||||
var attrs = _.extend({}, _.result(this, 'attributes'));
|
||||
if (this.id) attrs.id = _.result(this, 'id');
|
||||
if (this.className) attrs['class'] = _.result(this, 'className');
|
||||
this.setElement(this.make(_.result(this, 'tagName'), attrs), false);
|
||||
} else {
|
||||
this.setElement(this.el, false);
|
||||
this.setElement(_.result(this, 'el'), false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1351,7 +1371,7 @@
|
||||
|
||||
// Ensure that we have a URL.
|
||||
if (!options.url) {
|
||||
params.url = getValue(model, 'url') || urlError();
|
||||
params.url = _.result(model, 'url') || urlError();
|
||||
}
|
||||
|
||||
// Ensure that we have the appropriate request data.
|
||||
@@ -1368,14 +1388,14 @@
|
||||
|
||||
// For older servers, emulate HTTP by mimicking the HTTP method with `_method`
|
||||
// And an `X-HTTP-Method-Override` header.
|
||||
if (Backbone.emulateHTTP) {
|
||||
if (type === 'PUT' || type === 'DELETE') {
|
||||
if (Backbone.emulateJSON) params.data._method = type;
|
||||
params.type = 'POST';
|
||||
params.beforeSend = function(xhr) {
|
||||
xhr.setRequestHeader('X-HTTP-Method-Override', type);
|
||||
};
|
||||
}
|
||||
if (Backbone.emulateHTTP && (type === 'PUT' || type === 'DELETE')) {
|
||||
params.type = 'POST';
|
||||
if (Backbone.emulateJSON) params.data._method = type;
|
||||
var beforeSend = options.beforeSend;
|
||||
options.beforeSend = function(xhr) {
|
||||
xhr.setRequestHeader('X-HTTP-Method-Override', type);
|
||||
if (beforeSend) return beforeSend.apply(this, arguments);
|
||||
};
|
||||
}
|
||||
|
||||
// Don't process data on a non-GET request.
|
||||
@@ -1383,6 +1403,18 @@
|
||||
params.processData = false;
|
||||
}
|
||||
|
||||
var success = options.success;
|
||||
options.success = function(resp, status, xhr) {
|
||||
if (success) success(resp, status, xhr);
|
||||
model.trigger('sync', model, resp, options);
|
||||
};
|
||||
|
||||
var error = options.error;
|
||||
options.error = function(xhr, status, thrown) {
|
||||
if (error) error(model, xhr, options);
|
||||
model.trigger('error', model, xhr, options);
|
||||
};
|
||||
|
||||
// Make the request, allowing the user to override any Ajax options.
|
||||
return Backbone.ajax(_.extend(params, options));
|
||||
};
|
||||
@@ -1392,24 +1424,9 @@
|
||||
return Backbone.$.ajax.apply(Backbone.$, arguments);
|
||||
};
|
||||
|
||||
// Wrap an optional error callback with a fallback error event.
|
||||
Backbone.wrapError = function(onError, originalModel, options) {
|
||||
return function(model, resp) {
|
||||
resp = model === originalModel ? resp : model;
|
||||
if (onError) {
|
||||
onError(originalModel, resp, options);
|
||||
} else {
|
||||
originalModel.trigger('error', originalModel, resp, options);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
// Helpers
|
||||
// -------
|
||||
|
||||
// Shared empty constructor function to aid in prototype-chain creation.
|
||||
var ctor = function(){};
|
||||
|
||||
// Helper function to correctly set up the prototype chain, for subclasses.
|
||||
// Similar to `goog.inherits`, but uses a hash of prototype properties and
|
||||
// class properties to be extended.
|
||||
@@ -1420,45 +1437,34 @@
|
||||
// The constructor function for the new subclass is either defined by you
|
||||
// (the "constructor" property in your `extend` definition), or defaulted
|
||||
// by us to simply call the parent's constructor.
|
||||
if (protoProps && protoProps.hasOwnProperty('constructor')) {
|
||||
if (protoProps && _.has(protoProps, 'constructor')) {
|
||||
child = protoProps.constructor;
|
||||
} else {
|
||||
child = function(){ parent.apply(this, arguments); };
|
||||
}
|
||||
|
||||
// Inherit class (static) properties from parent.
|
||||
_.extend(child, parent);
|
||||
// Add static properties to the constructor function, if supplied.
|
||||
_.extend(child, parent, staticProps);
|
||||
|
||||
// Set the prototype chain to inherit from `parent`, without calling
|
||||
// `parent`'s constructor function.
|
||||
ctor.prototype = parent.prototype;
|
||||
child.prototype = new ctor();
|
||||
var Surrogate = function(){ this.constructor = child; };
|
||||
Surrogate.prototype = parent.prototype;
|
||||
child.prototype = new Surrogate;
|
||||
|
||||
// Add prototype properties (instance properties) to the subclass,
|
||||
// if supplied.
|
||||
if (protoProps) _.extend(child.prototype, protoProps);
|
||||
|
||||
// Add static properties to the constructor function, if supplied.
|
||||
if (staticProps) _.extend(child, staticProps);
|
||||
|
||||
// Correctly set child's `prototype.constructor`.
|
||||
child.prototype.constructor = child;
|
||||
|
||||
// Set a convenience property in case the parent's prototype is needed later.
|
||||
// Set a convenience property in case the parent's prototype is needed
|
||||
// later.
|
||||
child.__super__ = parent.prototype;
|
||||
|
||||
return child;
|
||||
};
|
||||
|
||||
// Set up inheritance for the model, collection, and view.
|
||||
Model.extend = Collection.extend = Router.extend = View.extend = extend;
|
||||
|
||||
// Helper function to get a value from a Backbone object as a property
|
||||
// or as a function.
|
||||
var getValue = function(object, prop) {
|
||||
if (!(object && object[prop])) return null;
|
||||
return _.isFunction(object[prop]) ? object[prop]() : object[prop];
|
||||
};
|
||||
// Set up inheritance for the model, collection, router, view and history.
|
||||
Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;
|
||||
|
||||
// Throw an error when a URL is needed, and none is supplied.
|
||||
var urlError = function() {
|
||||
|
||||
250
vendor/backbone/test/collection.js
vendored
250
vendor/backbone/test/collection.js
vendored
@@ -1,13 +1,12 @@
|
||||
$(document).ready(function() {
|
||||
|
||||
var lastRequest = null;
|
||||
var sync = Backbone.sync;
|
||||
|
||||
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'});
|
||||
@@ -15,23 +14,11 @@ $(document).ready(function() {
|
||||
e = null;
|
||||
col = new Backbone.Collection([a,b,c,d]);
|
||||
otherCol = new Backbone.Collection();
|
||||
|
||||
Backbone.sync = function(method, model, options) {
|
||||
lastRequest = {
|
||||
method: method,
|
||||
model: model,
|
||||
options: options
|
||||
};
|
||||
};
|
||||
},
|
||||
|
||||
teardown: function() {
|
||||
Backbone.sync = sync;
|
||||
}
|
||||
|
||||
});
|
||||
}));
|
||||
|
||||
test("Collection: new and sort", 7, function() {
|
||||
test("new and sort", 7, function() {
|
||||
equal(col.first(), a, "a should be first");
|
||||
equal(col.last(), d, "d should be last");
|
||||
col.comparator = function(a, b) {
|
||||
@@ -47,36 +34,37 @@ $(document).ready(function() {
|
||||
equal(col.length, 4);
|
||||
});
|
||||
|
||||
test("Collection: new and parse", 3, function() {
|
||||
var MyCol = Backbone.Collection.extend({
|
||||
// only save the models that have an even value.
|
||||
parse : function(data) {
|
||||
var onlyEven = [];
|
||||
_.each(data, function(datum) {
|
||||
if (datum.a % 2 === 0) {
|
||||
onlyEven.push(datum);
|
||||
}
|
||||
});
|
||||
|
||||
return onlyEven;
|
||||
}
|
||||
});
|
||||
anotherCol = new MyCol([
|
||||
{ a : 1 },{ a : 2 },{ a : 3 },{ a : 4 }
|
||||
], { parse : true });
|
||||
|
||||
equal(anotherCol.length, 2);
|
||||
equal(anotherCol.first().get('a'), 2)
|
||||
equal(anotherCol.last().get('a'), 4);
|
||||
test("String comparator.", 1, function() {
|
||||
var collection = new Backbone.Collection([
|
||||
{id: 3},
|
||||
{id: 1},
|
||||
{id: 2}
|
||||
], {comparator: 'id'});
|
||||
deepEqual(collection.pluck('id'), [1, 2, 3]);
|
||||
});
|
||||
|
||||
test("Collection: get, getByCid", 3, function() {
|
||||
test("new and parse", 3, function() {
|
||||
var Collection = Backbone.Collection.extend({
|
||||
parse : function(data) {
|
||||
return _.filter(data, function(datum) {
|
||||
return datum.a % 2 === 0;
|
||||
});
|
||||
}
|
||||
});
|
||||
var models = [{a: 1}, {a: 2}, {a: 3}, {a: 4}];
|
||||
var collection = new Collection(models, {parse: true});
|
||||
strictEqual(collection.length, 2);
|
||||
strictEqual(collection.first().get('a'), 2);
|
||||
strictEqual(collection.last().get('a'), 4);
|
||||
});
|
||||
|
||||
test("get, getByCid", 3, function() {
|
||||
equal(col.get(0), d);
|
||||
equal(col.get(2), b);
|
||||
equal(col.getByCid(col.first().cid), col.first());
|
||||
});
|
||||
|
||||
test("Collection: get with non-default ids", 2, function() {
|
||||
test("get with non-default ids", 2, function() {
|
||||
var col = new Backbone.Collection();
|
||||
var MongoModel = Backbone.Model.extend({
|
||||
idAttribute: '_id'
|
||||
@@ -88,7 +76,7 @@ $(document).ready(function() {
|
||||
equal(col.get(101), model);
|
||||
});
|
||||
|
||||
test("Collection: update index when id changes", 3, function() {
|
||||
test("update index when id changes", 3, function() {
|
||||
var col = new Backbone.Collection();
|
||||
col.add([
|
||||
{id : 0, name : 'one'},
|
||||
@@ -101,15 +89,15 @@ $(document).ready(function() {
|
||||
equal(col.get(101).get('name'), 'one');
|
||||
});
|
||||
|
||||
test("Collection: at", 1, function() {
|
||||
test("at", 1, function() {
|
||||
equal(col.at(2), c);
|
||||
});
|
||||
|
||||
test("Collection: pluck", 1, function() {
|
||||
test("pluck", 1, function() {
|
||||
equal(col.pluck('label').join(' '), 'a b c d');
|
||||
});
|
||||
|
||||
test("Collection: add", 11, function() {
|
||||
test("add", 10, function() {
|
||||
var added, opts, secondAdded;
|
||||
added = opts = secondAdded = null;
|
||||
e = new Backbone.Model({id: 10, label : 'e'});
|
||||
@@ -119,7 +107,6 @@ $(document).ready(function() {
|
||||
});
|
||||
col.on('add', function(model, collection, options){
|
||||
added = model.get('label');
|
||||
equal(options.index, 4);
|
||||
opts = options;
|
||||
});
|
||||
col.add(e, {amazing: true});
|
||||
@@ -141,7 +128,7 @@ $(document).ready(function() {
|
||||
equal(atCol.last(), h);
|
||||
});
|
||||
|
||||
test("Collection: add multiple models", 6, function() {
|
||||
test("add multiple models", 6, function() {
|
||||
var col = new Backbone.Collection([{at: 0}, {at: 1}, {at: 9}]);
|
||||
col.add([{at: 2}, {at: 3}, {at: 4}, {at: 5}, {at: 6}, {at: 7}, {at: 8}], {at: 2});
|
||||
for (var i = 0; i <= 5; i++) {
|
||||
@@ -149,7 +136,7 @@ $(document).ready(function() {
|
||||
}
|
||||
});
|
||||
|
||||
test("Collection: add; at should have preference over comparator", 1, function() {
|
||||
test("add; at should have preference over comparator", 1, function() {
|
||||
var Col = Backbone.Collection.extend({
|
||||
comparator: function(a,b) {
|
||||
return a.id > b.id ? -1 : 1;
|
||||
@@ -162,19 +149,19 @@ $(document).ready(function() {
|
||||
equal(col.pluck('id').join(' '), '3 1 2');
|
||||
});
|
||||
|
||||
test("Collection: can't add model to collection twice", function() {
|
||||
test("can't add model to collection twice", function() {
|
||||
var col = new Backbone.Collection([{id: 1}, {id: 2}, {id: 1}, {id: 2}, {id: 3}]);
|
||||
equal(col.pluck('id').join(' '), '1 2 3');
|
||||
});
|
||||
|
||||
test("Collection: can't add different model with same id to collection twice", 1, function() {
|
||||
test("can't add different model with same id to collection twice", 1, function() {
|
||||
var col = new Backbone.Collection;
|
||||
col.unshift({id: 101});
|
||||
col.add({id: 101});
|
||||
equal(col.length, 1);
|
||||
});
|
||||
|
||||
test("Collection: merge in duplicate models with {merge: true}", 3, function() {
|
||||
test("merge in duplicate models with {merge: true}", 3, function() {
|
||||
var col = new Backbone.Collection;
|
||||
col.add([{id: 1, name: 'Moe'}, {id: 2, name: 'Curly'}, {id: 3, name: 'Larry'}]);
|
||||
col.add({id: 1, name: 'Moses'});
|
||||
@@ -185,7 +172,7 @@ $(document).ready(function() {
|
||||
equal(col.first().get('name'), 'Tim');
|
||||
});
|
||||
|
||||
test("Collection: add model to multiple collections", 10, function() {
|
||||
test("add model to multiple collections", 10, function() {
|
||||
var counter = 0;
|
||||
var e = new Backbone.Model({id: 10, label : 'e'});
|
||||
e.on('add', function(model, collection) {
|
||||
@@ -213,7 +200,7 @@ $(document).ready(function() {
|
||||
equal(e.collection, colE);
|
||||
});
|
||||
|
||||
test("Collection: add model with parse", 1, function() {
|
||||
test("add model with parse", 1, function() {
|
||||
var Model = Backbone.Model.extend({
|
||||
parse: function(obj) {
|
||||
obj.value += 1;
|
||||
@@ -227,7 +214,7 @@ $(document).ready(function() {
|
||||
equal(col.at(0).get('value'), 2);
|
||||
});
|
||||
|
||||
test("Collection: add model to collection with sort()-style comparator", 3, function() {
|
||||
test("add model to collection with sort()-style comparator", 3, function() {
|
||||
var col = new Backbone.Collection;
|
||||
col.comparator = function(a, b) {
|
||||
return a.get('name') < b.get('name') ? -1 : 1;
|
||||
@@ -243,7 +230,7 @@ $(document).ready(function() {
|
||||
equal(col.indexOf(tom), 2);
|
||||
});
|
||||
|
||||
test("Collection: comparator that depends on `this`", 1, function() {
|
||||
test("comparator that depends on `this`", 2, function() {
|
||||
var col = new Backbone.Collection;
|
||||
col.negative = function(num) {
|
||||
return -num;
|
||||
@@ -252,10 +239,15 @@ $(document).ready(function() {
|
||||
return this.negative(a.id);
|
||||
};
|
||||
col.add([{id: 1}, {id: 2}, {id: 3}]);
|
||||
equal(col.pluck('id').join(' '), '3 2 1');
|
||||
deepEqual(col.pluck('id'), [3, 2, 1]);
|
||||
col.comparator = function(a, b) {
|
||||
return this.negative(b.id) - this.negative(a.id);
|
||||
};
|
||||
col.sort();
|
||||
deepEqual(col.pluck('id'), [1, 2, 3]);
|
||||
});
|
||||
|
||||
test("Collection: remove", 5, function() {
|
||||
test("remove", 5, function() {
|
||||
var removed = null;
|
||||
var otherRemoved = null;
|
||||
col.on('remove', function(model, col, options) {
|
||||
@@ -272,20 +264,20 @@ $(document).ready(function() {
|
||||
equal(otherRemoved, null);
|
||||
});
|
||||
|
||||
test("Collection: shift and pop", 2, function() {
|
||||
test("shift and pop", 2, function() {
|
||||
var col = new Backbone.Collection([{a: 'a'}, {b: 'b'}, {c: 'c'}]);
|
||||
equal(col.shift().get('a'), 'a');
|
||||
equal(col.pop().get('c'), 'c');
|
||||
});
|
||||
|
||||
test("Collection: slice", 2, function() {
|
||||
test("slice", 2, function() {
|
||||
var col = new Backbone.Collection([{a: 'a'}, {b: 'b'}, {c: 'c'}]);
|
||||
var array = col.slice(1, 3);
|
||||
equal(array.length, 2);
|
||||
equal(array[0].get('b'), 'b');
|
||||
});
|
||||
|
||||
test("Collection: events are unbound on remove", 3, function() {
|
||||
test("events are unbound on remove", 3, function() {
|
||||
var counter = 0;
|
||||
var dj = new Backbone.Model();
|
||||
var emcees = new Backbone.Collection([dj]);
|
||||
@@ -298,7 +290,7 @@ $(document).ready(function() {
|
||||
equal(counter, 1);
|
||||
});
|
||||
|
||||
test("Collection: remove in multiple collections", 7, function() {
|
||||
test("remove in multiple collections", 7, function() {
|
||||
var modelData = {
|
||||
id : 5,
|
||||
title : 'Othello'
|
||||
@@ -322,7 +314,7 @@ $(document).ready(function() {
|
||||
equal(passed, true);
|
||||
});
|
||||
|
||||
test("Collection: remove same model in multiple collection", 16, function() {
|
||||
test("remove same model in multiple collection", 16, function() {
|
||||
var counter = 0;
|
||||
var e = new Backbone.Model({id: 5, title: 'Othello'});
|
||||
e.on('remove', function(model, collection) {
|
||||
@@ -356,7 +348,7 @@ $(document).ready(function() {
|
||||
equal(counter, 2);
|
||||
});
|
||||
|
||||
test("Collection: model destroy removes from all collections", 3, function() {
|
||||
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({}); };
|
||||
var colE = new Backbone.Collection([e]);
|
||||
@@ -378,25 +370,29 @@ $(document).ready(function() {
|
||||
equal(undefined, e.collection);
|
||||
});
|
||||
|
||||
test("Collection: fetch", 4, function() {
|
||||
col.fetch();
|
||||
equal(lastRequest.method, 'read');
|
||||
equal(lastRequest.model, col);
|
||||
equal(lastRequest.options.parse, true);
|
||||
test("fetch", 4, function() {
|
||||
var collection = new Backbone.Collection;
|
||||
collection.url = '/test';
|
||||
collection.fetch();
|
||||
equal(this.syncArgs.method, 'read');
|
||||
equal(this.syncArgs.model, collection);
|
||||
equal(this.syncArgs.options.parse, true);
|
||||
|
||||
col.fetch({parse: false});
|
||||
equal(lastRequest.options.parse, false);
|
||||
collection.fetch({parse: false});
|
||||
equal(this.syncArgs.options.parse, false);
|
||||
});
|
||||
|
||||
test("Collection: create", 4, function() {
|
||||
var model = col.create({label: 'f'}, {wait: true});
|
||||
equal(lastRequest.method, 'create');
|
||||
equal(lastRequest.model, model);
|
||||
test("create", 4, function() {
|
||||
var collection = new Backbone.Collection;
|
||||
collection.url = '/test';
|
||||
var model = collection.create({label: 'f'}, {wait: true});
|
||||
equal(this.syncArgs.method, 'create');
|
||||
equal(this.syncArgs.model, model);
|
||||
equal(model.get('label'), 'f');
|
||||
equal(model.collection, col);
|
||||
equal(model.collection, collection);
|
||||
});
|
||||
|
||||
test("Collection: create enforces validation", 1, function() {
|
||||
test("create enforces validation", 1, function() {
|
||||
var ValidatingModel = Backbone.Model.extend({
|
||||
validate: function(attrs) {
|
||||
return "fail";
|
||||
@@ -409,7 +405,7 @@ $(document).ready(function() {
|
||||
equal(col.create({"foo":"bar"}), false);
|
||||
});
|
||||
|
||||
test("Collection: a failing create runs the error callback", 1, function() {
|
||||
test("a failing create runs the error callback", 1, function() {
|
||||
var ValidatingModel = Backbone.Model.extend({
|
||||
validate: function(attrs) {
|
||||
return "fail";
|
||||
@@ -425,7 +421,7 @@ $(document).ready(function() {
|
||||
equal(flag, true);
|
||||
});
|
||||
|
||||
test("collection: initialize", 1, function() {
|
||||
test("initialize", 1, function() {
|
||||
var Collection = Backbone.Collection.extend({
|
||||
initialize: function() {
|
||||
this.one = 1;
|
||||
@@ -435,11 +431,11 @@ $(document).ready(function() {
|
||||
equal(coll.one, 1);
|
||||
});
|
||||
|
||||
test("Collection: toJSON", 1, function() {
|
||||
test("toJSON", 1, function() {
|
||||
equal(JSON.stringify(col), '[{"id":3,"label":"a"},{"id":2,"label":"b"},{"id":1,"label":"c"},{"id":0,"label":"d"}]');
|
||||
});
|
||||
|
||||
test("Collection: where", 6, function() {
|
||||
test("where", 6, function() {
|
||||
var coll = new Backbone.Collection([
|
||||
{a: 1},
|
||||
{a: 1},
|
||||
@@ -455,7 +451,7 @@ $(document).ready(function() {
|
||||
equal(coll.where({a: 1, b: 2}).length, 1);
|
||||
});
|
||||
|
||||
test("Collection: Underscore methods", 13, 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);
|
||||
@@ -475,7 +471,7 @@ $(document).ready(function() {
|
||||
[4, 0]);
|
||||
});
|
||||
|
||||
test("Collection: reset", 10, function() {
|
||||
test("reset", 10, function() {
|
||||
var resetCount = 0;
|
||||
var models = col.models;
|
||||
col.on('reset', function() { resetCount += 1; });
|
||||
@@ -494,7 +490,7 @@ $(document).ready(function() {
|
||||
ok(_.isEqual(col.last().attributes, d.attributes));
|
||||
});
|
||||
|
||||
test("Collection: reset passes caller options", 3, function() {
|
||||
test("reset passes caller options", 3, function() {
|
||||
var Model = Backbone.Model.extend({
|
||||
initialize: function(attrs, options) {
|
||||
this.model_parameter = options.model_parameter;
|
||||
@@ -508,14 +504,14 @@ $(document).ready(function() {
|
||||
});
|
||||
});
|
||||
|
||||
test("Collection: trigger custom events on models", 1, function() {
|
||||
test("trigger custom events on models", 1, function() {
|
||||
var fired = null;
|
||||
a.on("custom", function() { fired = true; });
|
||||
a.trigger("custom");
|
||||
equal(fired, true);
|
||||
});
|
||||
|
||||
test("Collection: add does not alter arguments", 2, function(){
|
||||
test("add does not alter arguments", 2, function(){
|
||||
var attrs = {};
|
||||
var models = [attrs];
|
||||
new Backbone.Collection().add(models);
|
||||
@@ -524,16 +520,17 @@ $(document).ready(function() {
|
||||
});
|
||||
|
||||
test("#714: access `model.collection` in a brand new model.", 2, function() {
|
||||
var col = new Backbone.Collection;
|
||||
var collection = new Backbone.Collection;
|
||||
collection.url = '/test';
|
||||
var Model = Backbone.Model.extend({
|
||||
set: function(attrs) {
|
||||
equal(attrs.prop, 'value');
|
||||
equal(this.collection, col);
|
||||
equal(this.collection, collection);
|
||||
return this;
|
||||
}
|
||||
});
|
||||
col.model = Model;
|
||||
col.create({prop: 'value'});
|
||||
collection.model = Model;
|
||||
collection.create({prop: 'value'});
|
||||
});
|
||||
|
||||
test("#574, remove its own reference to the .models array.", 2, function() {
|
||||
@@ -565,24 +562,7 @@ $(document).ready(function() {
|
||||
});
|
||||
});
|
||||
|
||||
test("Collection: index with comparator", 4, function() {
|
||||
var counter = 0;
|
||||
var col = new Backbone.Collection([{id: 2}, {id: 4}], {
|
||||
comparator: function(model){ return model.id; }
|
||||
}).on('add', function(model, colleciton, options){
|
||||
if (model.id == 1) {
|
||||
equal(options.index, 0);
|
||||
equal(counter++, 0);
|
||||
}
|
||||
if (model.id == 3) {
|
||||
equal(options.index, 2);
|
||||
equal(counter++, 1);
|
||||
}
|
||||
});
|
||||
col.add([{id: 3}, {id: 1}]);
|
||||
});
|
||||
|
||||
test("Collection: throwing during add leaves consistent state", 4, function() {
|
||||
test("throwing during add leaves consistent state", 4, function() {
|
||||
var col = new Backbone.Collection();
|
||||
col.on('test', function() { ok(false); });
|
||||
col.model = Backbone.Model.extend({
|
||||
@@ -596,7 +576,7 @@ $(document).ready(function() {
|
||||
equal(col.length, 0);
|
||||
});
|
||||
|
||||
test("Collection: multiple copies of the same model", 3, function() {
|
||||
test("multiple copies of the same model", 3, function() {
|
||||
var col = new Backbone.Collection();
|
||||
var model = new Backbone.Model();
|
||||
col.add([model, model]);
|
||||
@@ -629,7 +609,7 @@ $(document).ready(function() {
|
||||
ok(!collection.get('undefined'));
|
||||
});
|
||||
|
||||
test("Collection: falsy comparator", 4, function(){
|
||||
test("falsy comparator", 4, function(){
|
||||
var Col = Backbone.Collection.extend({
|
||||
comparator: function(model){ return model.id; }
|
||||
});
|
||||
@@ -659,20 +639,15 @@ $(document).ready(function() {
|
||||
});
|
||||
|
||||
test("#1412 - Trigger 'sync' event.", 2, function() {
|
||||
var collection = new Backbone.Collection([], {
|
||||
model: Backbone.Model.extend({
|
||||
sync: function(method, model, options) {
|
||||
options.success();
|
||||
}
|
||||
})
|
||||
});
|
||||
collection.sync = function(method, model, options) { options.success(); };
|
||||
var collection = new Backbone.Collection;
|
||||
collection.url = '/test';
|
||||
collection.on('sync', function() { ok(true); });
|
||||
Backbone.ajax = function(settings){ settings.success(); };
|
||||
collection.fetch();
|
||||
collection.create({id: 1});
|
||||
});
|
||||
|
||||
test("#1447 - create with wait adds model.", function() {
|
||||
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(); };
|
||||
@@ -680,7 +655,7 @@ $(document).ready(function() {
|
||||
collection.create(model, {wait: true});
|
||||
});
|
||||
|
||||
test("#1448 - add sorts collection after merge.", function() {
|
||||
test("#1448 - add sorts collection after merge.", 1, function() {
|
||||
var collection = new Backbone.Collection([
|
||||
{id: 1, x: 1},
|
||||
{id: 2, x: 2}
|
||||
@@ -689,4 +664,41 @@ $(document).ready(function() {
|
||||
collection.add({id: 1, x: 3}, {merge: true});
|
||||
deepEqual(collection.pluck('id'), [2, 1]);
|
||||
});
|
||||
|
||||
test("#1655 - groupBy can be used with a string argument.", 3, function() {
|
||||
var collection = new Backbone.Collection([{x: 1}, {x: 2}]);
|
||||
var grouped = collection.groupBy('x');
|
||||
strictEqual(_.keys(grouped).length, 2);
|
||||
strictEqual(grouped[1][0].get('x'), 1);
|
||||
strictEqual(grouped[2][0].get('x'), 2);
|
||||
});
|
||||
|
||||
test("#1655 - sortBy can be used with a string argument.", 1, function() {
|
||||
var collection = new Backbone.Collection([{x: 3}, {x: 1}, {x: 2}]);
|
||||
var values = _.map(collection.sortBy('x'), function(model) {
|
||||
return model.get('x');
|
||||
});
|
||||
deepEqual(values, [1, 2, 3]);
|
||||
});
|
||||
|
||||
test("#1604 - Removal during iteration.", 0, function() {
|
||||
var collection = new Backbone.Collection([{}, {}]);
|
||||
collection.on('add', function() {
|
||||
collection.at(0).destroy();
|
||||
});
|
||||
collection.add({}, {at: 0});
|
||||
});
|
||||
|
||||
test("#1638 - `sort` during `add` triggers correctly.", function() {
|
||||
var collection = new Backbone.Collection;
|
||||
collection.comparator = function(model) { return model.get('x'); };
|
||||
var added = [];
|
||||
collection.on('add', function(model) {
|
||||
model.set({x: 3});
|
||||
collection.sort();
|
||||
added.push(model.id);
|
||||
});
|
||||
collection.add([{id: 1, x: 1}, {id: 2, x: 2}]);
|
||||
deepEqual(added, [1, 2]);
|
||||
});
|
||||
});
|
||||
|
||||
39
vendor/backbone/test/environment.js
vendored
Normal file
39
vendor/backbone/test/environment.js
vendored
Normal file
@@ -0,0 +1,39 @@
|
||||
(function() {
|
||||
|
||||
var Environment = this.Environment = function(){};
|
||||
|
||||
_.extend(Environment.prototype, {
|
||||
|
||||
ajax: Backbone.ajax,
|
||||
|
||||
sync: Backbone.sync,
|
||||
|
||||
setup: function() {
|
||||
var env = this;
|
||||
|
||||
// Capture ajax settings for comparison.
|
||||
Backbone.ajax = function(settings) {
|
||||
env.ajaxSettings = settings;
|
||||
};
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
})();
|
||||
20
vendor/backbone/test/events.js
vendored
20
vendor/backbone/test/events.js
vendored
@@ -2,7 +2,7 @@ $(document).ready(function() {
|
||||
|
||||
module("Backbone.Events");
|
||||
|
||||
test("Events: on and trigger", 2, function() {
|
||||
test("on and trigger", 2, function() {
|
||||
var obj = { counter: 0 };
|
||||
_.extend(obj,Backbone.Events);
|
||||
obj.on('event', function() { obj.counter += 1; });
|
||||
@@ -15,7 +15,7 @@ $(document).ready(function() {
|
||||
equal(obj.counter, 5, 'counter should be incremented five times.');
|
||||
});
|
||||
|
||||
test("Events: binding and triggering multiple events", 4, function() {
|
||||
test("binding and triggering multiple events", 4, function() {
|
||||
var obj = { counter: 0 };
|
||||
_.extend(obj,Backbone.Events);
|
||||
|
||||
@@ -35,7 +35,7 @@ $(document).ready(function() {
|
||||
equal(obj.counter, 5);
|
||||
});
|
||||
|
||||
test("Events: trigger all for each event", 3, function() {
|
||||
test("trigger all for each event", 3, function() {
|
||||
var a, b, obj = { counter: 0 };
|
||||
_.extend(obj, Backbone.Events);
|
||||
obj.on('all', function(event) {
|
||||
@@ -49,7 +49,7 @@ $(document).ready(function() {
|
||||
equal(obj.counter, 2);
|
||||
});
|
||||
|
||||
test("Events: on, then unbind all functions", 1, function() {
|
||||
test("on, then unbind all functions", 1, function() {
|
||||
var obj = { counter: 0 };
|
||||
_.extend(obj,Backbone.Events);
|
||||
var callback = function() { obj.counter += 1; };
|
||||
@@ -60,7 +60,7 @@ $(document).ready(function() {
|
||||
equal(obj.counter, 1, 'counter should have only been incremented once.');
|
||||
});
|
||||
|
||||
test("Events: bind two callbacks, unbind only one", 2, function() {
|
||||
test("bind two callbacks, unbind only one", 2, function() {
|
||||
var obj = { counterA: 0, counterB: 0 };
|
||||
_.extend(obj,Backbone.Events);
|
||||
var callback = function() { obj.counterA += 1; };
|
||||
@@ -73,7 +73,7 @@ $(document).ready(function() {
|
||||
equal(obj.counterB, 2, 'counterB should have been incremented twice.');
|
||||
});
|
||||
|
||||
test("Events: unbind a callback in the midst of it firing", 1, function() {
|
||||
test("unbind a callback in the midst of it firing", 1, function() {
|
||||
var obj = {counter: 0};
|
||||
_.extend(obj, Backbone.Events);
|
||||
var callback = function() {
|
||||
@@ -87,7 +87,7 @@ $(document).ready(function() {
|
||||
equal(obj.counter, 1, 'the callback should have been unbound.');
|
||||
});
|
||||
|
||||
test("Events: two binds that unbind themeselves", 2, function() {
|
||||
test("two binds that unbind themeselves", 2, function() {
|
||||
var obj = { counterA: 0, counterB: 0 };
|
||||
_.extend(obj,Backbone.Events);
|
||||
var incrA = function(){ obj.counterA += 1; obj.off('event', incrA); };
|
||||
@@ -101,7 +101,7 @@ $(document).ready(function() {
|
||||
equal(obj.counterB, 1, 'counterB should have only been incremented once.');
|
||||
});
|
||||
|
||||
test("Events: bind a callback with a supplied context", 1, function () {
|
||||
test("bind a callback with a supplied context", 1, function () {
|
||||
var TestClass = function () {
|
||||
return this;
|
||||
};
|
||||
@@ -114,7 +114,7 @@ $(document).ready(function() {
|
||||
obj.trigger('event');
|
||||
});
|
||||
|
||||
test("Events: nested trigger with unbind", 1, function () {
|
||||
test("nested trigger with unbind", 1, function () {
|
||||
var obj = { counter: 0 };
|
||||
_.extend(obj, Backbone.Events);
|
||||
var incr1 = function(){ obj.counter += 1; obj.off('event', incr1); obj.trigger('event'); };
|
||||
@@ -125,7 +125,7 @@ $(document).ready(function() {
|
||||
equal(obj.counter, 3, 'counter should have been incremented three times');
|
||||
});
|
||||
|
||||
test("Events: callback list is not altered during trigger", 2, function () {
|
||||
test("callback list is not altered during trigger", 2, function () {
|
||||
var counter = 0, obj = _.extend({}, Backbone.Events);
|
||||
var incr = function(){ counter++; };
|
||||
obj.on('event', function(){ obj.on('event', incr).on('all', incr); })
|
||||
|
||||
231
vendor/backbone/test/model.js
vendored
231
vendor/backbone/test/model.js
vendored
@@ -1,22 +1,15 @@
|
||||
$(document).ready(function() {
|
||||
|
||||
// Variable to catch the last request.
|
||||
var lastRequest = null;
|
||||
// Variable to catch ajax params.
|
||||
var ajaxParams = null;
|
||||
var sync = Backbone.sync;
|
||||
var ajax = Backbone.ajax;
|
||||
var urlRoot = null;
|
||||
|
||||
var proxy = Backbone.Model.extend();
|
||||
var klass = Backbone.Collection.extend({
|
||||
url : function() { return '/collection'; }
|
||||
});
|
||||
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",
|
||||
@@ -25,29 +18,11 @@ $(document).ready(function() {
|
||||
});
|
||||
collection = new klass();
|
||||
collection.add(doc);
|
||||
|
||||
Backbone.sync = function(method, model, options) {
|
||||
lastRequest = {
|
||||
method: method,
|
||||
model: model,
|
||||
options: options
|
||||
};
|
||||
sync.apply(this, arguments);
|
||||
};
|
||||
Backbone.ajax = function(params) { ajaxParams = params; };
|
||||
urlRoot = Backbone.Model.prototype.urlRoot;
|
||||
Backbone.Model.prototype.urlRoot = '/';
|
||||
},
|
||||
|
||||
teardown: function() {
|
||||
Backbone.sync = sync;
|
||||
Backbone.ajax = ajax;
|
||||
Backbone.Model.prototype.urlRoot = urlRoot;
|
||||
}
|
||||
|
||||
});
|
||||
}));
|
||||
|
||||
test("Model: initialize", 3, function() {
|
||||
test("initialize", 3, function() {
|
||||
var Model = Backbone.Model.extend({
|
||||
initialize: function() {
|
||||
this.one = 1;
|
||||
@@ -59,7 +34,7 @@ $(document).ready(function() {
|
||||
equal(model.collection, collection);
|
||||
});
|
||||
|
||||
test("Model: initialize with attributes and options", 1, function() {
|
||||
test("initialize with attributes and options", 1, function() {
|
||||
var Model = Backbone.Model.extend({
|
||||
initialize: function(attributes, options) {
|
||||
this.one = options.one;
|
||||
@@ -69,7 +44,7 @@ $(document).ready(function() {
|
||||
equal(model.one, 1);
|
||||
});
|
||||
|
||||
test("Model: initialize with parsed attributes", 1, function() {
|
||||
test("initialize with parsed attributes", 1, function() {
|
||||
var Model = Backbone.Model.extend({
|
||||
parse: function(obj) {
|
||||
obj.value += 1;
|
||||
@@ -80,7 +55,18 @@ $(document).ready(function() {
|
||||
equal(model.get('value'), 2);
|
||||
});
|
||||
|
||||
test("Model: url", 3, function() {
|
||||
test("parse can return null", 1, function() {
|
||||
var Model = Backbone.Model.extend({
|
||||
parse: function(obj) {
|
||||
obj.value += 1;
|
||||
return null;
|
||||
}
|
||||
});
|
||||
var model = new Model({value: 1}, {parse: true});
|
||||
equal(JSON.stringify(model.toJSON()), "{}");
|
||||
});
|
||||
|
||||
test("url", 3, function() {
|
||||
doc.urlRoot = null;
|
||||
equal(doc.url(), '/collection/1-the-tempest');
|
||||
doc.collection.url = '/collection/';
|
||||
@@ -90,7 +76,7 @@ $(document).ready(function() {
|
||||
doc.collection = collection;
|
||||
});
|
||||
|
||||
test("Model: url when using urlRoot, and uri encoding", 2, function() {
|
||||
test("url when using urlRoot, and uri encoding", 2, function() {
|
||||
var Model = Backbone.Model.extend({
|
||||
urlRoot: '/collection'
|
||||
});
|
||||
@@ -100,7 +86,7 @@ $(document).ready(function() {
|
||||
equal(model.url(), '/collection/%2B1%2B');
|
||||
});
|
||||
|
||||
test("Model: url when using urlRoot as a function to determine urlRoot at runtime", 2, function() {
|
||||
test("url when using urlRoot as a function to determine urlRoot at runtime", 2, function() {
|
||||
var Model = Backbone.Model.extend({
|
||||
urlRoot: function() {
|
||||
return '/nested/' + this.get('parent_id') + '/collection';
|
||||
@@ -113,7 +99,7 @@ $(document).ready(function() {
|
||||
equal(model.url(), '/nested/1/collection/2');
|
||||
});
|
||||
|
||||
test("Model: clone", 8, function() {
|
||||
test("clone", 8, function() {
|
||||
var a = new Backbone.Model({ 'foo': 1, 'bar': 2, 'baz': 3});
|
||||
var b = a.clone();
|
||||
equal(a.get('foo'), 1);
|
||||
@@ -127,7 +113,7 @@ $(document).ready(function() {
|
||||
equal(b.get('foo'), 1, "Changing a parent attribute does not change the clone.");
|
||||
});
|
||||
|
||||
test("Model: isNew", 6, function() {
|
||||
test("isNew", 6, function() {
|
||||
var a = new Backbone.Model({ 'foo': 1, 'bar': 2, 'baz': 3});
|
||||
ok(a.isNew(), "it should be new");
|
||||
a = new Backbone.Model({ 'foo': 1, 'bar': 2, 'baz': 3, 'id': -5 });
|
||||
@@ -139,12 +125,12 @@ $(document).ready(function() {
|
||||
ok(!new Backbone.Model({ 'id': -5 }).isNew(), "is false for a negative integer");
|
||||
});
|
||||
|
||||
test("Model: get", 2, function() {
|
||||
test("get", 2, function() {
|
||||
equal(doc.get('title'), 'The Tempest');
|
||||
equal(doc.get('author'), 'Bill Shakespeare');
|
||||
});
|
||||
|
||||
test("Model: escape", 5, function() {
|
||||
test("escape", 5, function() {
|
||||
equal(doc.escape('title'), 'The Tempest');
|
||||
doc.set({audience: 'Bill & Bob'});
|
||||
equal(doc.escape('audience'), 'Bill & Bob');
|
||||
@@ -156,7 +142,7 @@ $(document).ready(function() {
|
||||
equal(doc.escape('audience'), '');
|
||||
});
|
||||
|
||||
test("Model: has", 10, function() {
|
||||
test("has", 10, function() {
|
||||
var model = new Backbone.Model();
|
||||
|
||||
strictEqual(model.has('name'), false);
|
||||
@@ -186,7 +172,7 @@ $(document).ready(function() {
|
||||
strictEqual(model.has('undefined'), false);
|
||||
});
|
||||
|
||||
test("Model: set and unset", 8, function() {
|
||||
test("set and unset", 8, function() {
|
||||
var a = new Backbone.Model({id: 'id', foo: 1, bar: 2, baz: 3});
|
||||
var changeCount = 0;
|
||||
a.on("change:foo", function() { changeCount += 1; });
|
||||
@@ -209,7 +195,7 @@ $(document).ready(function() {
|
||||
equal(a.id, undefined, "Unsetting the id should remove the id property.");
|
||||
});
|
||||
|
||||
test("Model: multiple unsets", 1, function() {
|
||||
test("multiple unsets", 1, function() {
|
||||
var i = 0;
|
||||
var counter = function(){ i++; };
|
||||
var model = new Backbone.Model({a: 1});
|
||||
@@ -220,7 +206,7 @@ $(document).ready(function() {
|
||||
equal(i, 2, 'Unset does not fire an event for missing attributes.');
|
||||
});
|
||||
|
||||
test("Model: unset and changedAttributes", 2, function() {
|
||||
test("unset and changedAttributes", 2, function() {
|
||||
var model = new Backbone.Model({a: 1});
|
||||
model.unset('a', {silent: true});
|
||||
var changedAttributes = model.changedAttributes();
|
||||
@@ -230,7 +216,7 @@ $(document).ready(function() {
|
||||
ok('a' in changedAttributes, 'changedAttributes should contain unset properties when running changedAttributes again after an unset.');
|
||||
});
|
||||
|
||||
test("Model: using a non-default id attribute.", 5, function() {
|
||||
test("using a non-default id attribute.", 5, function() {
|
||||
var MongoModel = Backbone.Model.extend({idAttribute : '_id'});
|
||||
var model = new MongoModel({id: 'eye-dee', _id: 25, title: 'Model'});
|
||||
equal(model.get('id'), 'eye-dee');
|
||||
@@ -241,13 +227,13 @@ $(document).ready(function() {
|
||||
equal(model.isNew(), true);
|
||||
});
|
||||
|
||||
test("Model: set an empty string", 1, function() {
|
||||
test("set an empty string", 1, function() {
|
||||
var model = new Backbone.Model({name : "Model"});
|
||||
model.set({name : ''});
|
||||
equal(model.get('name'), '');
|
||||
});
|
||||
|
||||
test("Model: clear", 3, function() {
|
||||
test("clear", 3, function() {
|
||||
var changed;
|
||||
var model = new Backbone.Model({id: 1, name : "Model"});
|
||||
model.on("change:name", function(){ changed = true; });
|
||||
@@ -260,7 +246,7 @@ $(document).ready(function() {
|
||||
equal(model.get('name'), undefined);
|
||||
});
|
||||
|
||||
test("Model: defaults", 4, function() {
|
||||
test("defaults", 4, function() {
|
||||
var Defaulted = Backbone.Model.extend({
|
||||
defaults: {
|
||||
"one": 1,
|
||||
@@ -283,7 +269,7 @@ $(document).ready(function() {
|
||||
equal(model.get('two'), null);
|
||||
});
|
||||
|
||||
test("Model: change, hasChanged, changedAttributes, previous, previousAttributes", 12, function() {
|
||||
test("change, hasChanged, changedAttributes, previous, previousAttributes", 12, function() {
|
||||
var model = new Backbone.Model({name : "Tim", age : 10});
|
||||
equal(model.changedAttributes(), false);
|
||||
model.on('change', function() {
|
||||
@@ -304,14 +290,14 @@ $(document).ready(function() {
|
||||
|
||||
});
|
||||
|
||||
test("Model: changedAttributes", 3, function() {
|
||||
test("changedAttributes", 3, function() {
|
||||
var model = new Backbone.Model({a: 'a', b: 'b'});
|
||||
equal(model.changedAttributes(), false);
|
||||
equal(model.changedAttributes({a: 'a'}), false);
|
||||
equal(model.changedAttributes({a: 'b'}).a, 'b');
|
||||
});
|
||||
|
||||
test("Model: change with options", 2, function() {
|
||||
test("change with options", 2, function() {
|
||||
var value;
|
||||
var model = new Backbone.Model({name: 'Rob'});
|
||||
model.on('change', function(model, options) {
|
||||
@@ -324,7 +310,7 @@ $(document).ready(function() {
|
||||
equal(value, 'Ms. Sue');
|
||||
});
|
||||
|
||||
test("Model: change after initialize", 1, function () {
|
||||
test("change after initialize", 1, function () {
|
||||
var changed = 0;
|
||||
var attrs = {id: 1, label: 'c'};
|
||||
var obj = new Backbone.Model(attrs);
|
||||
@@ -333,16 +319,18 @@ $(document).ready(function() {
|
||||
equal(changed, 0);
|
||||
});
|
||||
|
||||
test("Model: save within change event", 1, function () {
|
||||
test("save within change event", 1, function () {
|
||||
var env = this;
|
||||
var model = new Backbone.Model({firstName : "Taylor", lastName: "Swift"});
|
||||
model.url = '/test';
|
||||
model.on('change', function () {
|
||||
model.save();
|
||||
ok(_.isEqual(lastRequest.model, model));
|
||||
ok(_.isEqual(env.syncArgs.model, model));
|
||||
});
|
||||
model.set({lastName: 'Hicks'});
|
||||
});
|
||||
|
||||
test("Model: validate after save", 1, function() {
|
||||
test("validate after save", 1, function() {
|
||||
var lastError, model = new Backbone.Model();
|
||||
model.validate = function(attrs) {
|
||||
if (attrs.admin) return "Can't change admin status.";
|
||||
@@ -357,7 +345,7 @@ $(document).ready(function() {
|
||||
equal(lastError, "Can't change admin status.");
|
||||
});
|
||||
|
||||
test("Model: isValid", 5, function() {
|
||||
test("isValid", 5, function() {
|
||||
var model = new Backbone.Model({valid: true});
|
||||
model.validate = function(attrs) {
|
||||
if (!attrs.valid) return "invalid";
|
||||
@@ -369,13 +357,13 @@ $(document).ready(function() {
|
||||
equal(model.isValid(), false);
|
||||
});
|
||||
|
||||
test("Model: save", 2, function() {
|
||||
test("save", 2, function() {
|
||||
doc.save({title : "Henry V"});
|
||||
equal(lastRequest.method, 'update');
|
||||
ok(_.isEqual(lastRequest.model, doc));
|
||||
equal(this.syncArgs.method, 'update');
|
||||
ok(_.isEqual(this.syncArgs.model, doc));
|
||||
});
|
||||
|
||||
test("Model: save in positional style", 1, function() {
|
||||
test("save in positional style", 1, function() {
|
||||
var model = new Backbone.Model();
|
||||
model.sync = function(method, model, options) {
|
||||
options.success();
|
||||
@@ -386,29 +374,29 @@ $(document).ready(function() {
|
||||
|
||||
|
||||
|
||||
test("Model: fetch", 2, function() {
|
||||
test("fetch", 2, function() {
|
||||
doc.fetch();
|
||||
equal(lastRequest.method, 'read');
|
||||
ok(_.isEqual(lastRequest.model, doc));
|
||||
equal(this.syncArgs.method, 'read');
|
||||
ok(_.isEqual(this.syncArgs.model, doc));
|
||||
});
|
||||
|
||||
test("Model: destroy", 3, function() {
|
||||
test("destroy", 3, function() {
|
||||
doc.destroy();
|
||||
equal(lastRequest.method, 'delete');
|
||||
ok(_.isEqual(lastRequest.model, doc));
|
||||
equal(this.syncArgs.method, 'delete');
|
||||
ok(_.isEqual(this.syncArgs.model, doc));
|
||||
|
||||
var newModel = new Backbone.Model;
|
||||
equal(newModel.destroy(), false);
|
||||
});
|
||||
|
||||
test("Model: non-persisted destroy", 1, function() {
|
||||
test("non-persisted destroy", 1, function() {
|
||||
var a = new Backbone.Model({ 'foo': 1, 'bar': 2, 'baz': 3});
|
||||
a.sync = function() { throw "should not be called"; };
|
||||
a.destroy();
|
||||
ok(true, "non-persisted model should not call sync");
|
||||
});
|
||||
|
||||
test("Model: validate", 7, function() {
|
||||
test("validate", 7, function() {
|
||||
var lastError;
|
||||
var model = new Backbone.Model();
|
||||
model.validate = function(attrs) {
|
||||
@@ -429,7 +417,7 @@ $(document).ready(function() {
|
||||
equal(model.get('a'), 100);
|
||||
});
|
||||
|
||||
test("Model: validate on unset and clear", 6, function() {
|
||||
test("validate on unset and clear", 6, function() {
|
||||
var error;
|
||||
var model = new Backbone.Model({name: "One"});
|
||||
model.validate = function(attrs) {
|
||||
@@ -451,7 +439,7 @@ $(document).ready(function() {
|
||||
equal(model.get('name'), undefined);
|
||||
});
|
||||
|
||||
test("Model: validate with error callback", 8, function() {
|
||||
test("validate with error callback", 8, function() {
|
||||
var lastError, boundError;
|
||||
var model = new Backbone.Model();
|
||||
model.validate = function(attrs) {
|
||||
@@ -472,10 +460,10 @@ $(document).ready(function() {
|
||||
equal(result, false);
|
||||
equal(model.get('a'), 100);
|
||||
equal(lastError, "Can't change admin status.");
|
||||
equal(boundError, undefined);
|
||||
equal(boundError, true);
|
||||
});
|
||||
|
||||
test("Model: defaults always extend attrs (#459)", 2, function() {
|
||||
test("defaults always extend attrs (#459)", 2, function() {
|
||||
var Defaulted = Backbone.Model.extend({
|
||||
defaults: {one: 1},
|
||||
initialize : function(attrs, opts) {
|
||||
@@ -486,7 +474,7 @@ $(document).ready(function() {
|
||||
var emptyattrs = new Defaulted();
|
||||
});
|
||||
|
||||
test("Model: Inherit class properties", 6, function() {
|
||||
test("Inherit class properties", 6, function() {
|
||||
var Parent = Backbone.Model.extend({
|
||||
instancePropSame: function() {},
|
||||
instancePropDiff: function() {}
|
||||
@@ -510,7 +498,7 @@ $(document).ready(function() {
|
||||
notEqual(Child.prototype.instancePropDiff, undefined);
|
||||
});
|
||||
|
||||
test("Model: Nested change events don't clobber previous attributes", 4, function() {
|
||||
test("Nested change events don't clobber previous attributes", 4, function() {
|
||||
new Backbone.Model()
|
||||
.on('change:state', function(model, newState) {
|
||||
equal(model.previous('state'), undefined);
|
||||
@@ -595,8 +583,9 @@ $(document).ready(function() {
|
||||
|
||||
test("save with `wait` succeeds without `validate`", 1, function() {
|
||||
var model = new Backbone.Model();
|
||||
model.url = '/test';
|
||||
model.save({x: 1}, {wait: true});
|
||||
ok(lastRequest.model === model);
|
||||
ok(this.syncArgs.model === model);
|
||||
});
|
||||
|
||||
test("`hasChanged` for falsey keys", 2, function() {
|
||||
@@ -616,18 +605,20 @@ $(document).ready(function() {
|
||||
test("`save` with `wait` sends correct attributes", 5, function() {
|
||||
var changed = 0;
|
||||
var model = new Backbone.Model({x: 1, y: 2});
|
||||
model.url = '/test';
|
||||
model.on('change:x', function() { changed++; });
|
||||
model.save({x: 3}, {wait: true});
|
||||
deepEqual(JSON.parse(ajaxParams.data), {x: 3, y: 2});
|
||||
deepEqual(JSON.parse(this.ajaxSettings.data), {x: 3, y: 2});
|
||||
equal(model.get('x'), 1);
|
||||
equal(changed, 0);
|
||||
lastRequest.options.success({});
|
||||
this.syncArgs.options.success({});
|
||||
equal(model.get('x'), 3);
|
||||
equal(changed, 1);
|
||||
});
|
||||
|
||||
test("a failed `save` with `wait` doesn't leave attributes behind", 1, function() {
|
||||
var model = new Backbone.Model;
|
||||
model.url = '/test';
|
||||
model.save({x: 1}, {wait: true});
|
||||
equal(model.get('x'), void 0);
|
||||
});
|
||||
@@ -644,6 +635,7 @@ $(document).ready(function() {
|
||||
|
||||
test("save with wait validates attributes", 1, function() {
|
||||
var model = new Backbone.Model();
|
||||
model.url = '/test';
|
||||
model.validate = function() { ok(true); };
|
||||
model.save({x: 1}, {wait: true});
|
||||
});
|
||||
@@ -759,9 +751,9 @@ $(document).ready(function() {
|
||||
model.set({b: 2}, {silent: true});
|
||||
});
|
||||
model.set({b: 0});
|
||||
deepEqual(changes, [0, 1, 1]);
|
||||
deepEqual(changes, [0, 1]);
|
||||
model.change();
|
||||
deepEqual(changes, [0, 1, 1, 2, 1]);
|
||||
deepEqual(changes, [0, 1, 2, 1]);
|
||||
});
|
||||
|
||||
test("nested set multiple times", 1, function() {
|
||||
@@ -776,24 +768,6 @@ $(document).ready(function() {
|
||||
model.set({a: true});
|
||||
});
|
||||
|
||||
test("Backbone.wrapError triggers `'error'`", 12, function() {
|
||||
var resp = {};
|
||||
var options = {};
|
||||
var model = new Backbone.Model();
|
||||
model.on('error', error);
|
||||
var callback = Backbone.wrapError(null, model, options);
|
||||
callback(model, resp);
|
||||
callback(resp);
|
||||
callback = Backbone.wrapError(error, model, options);
|
||||
callback(model, resp);
|
||||
callback(resp);
|
||||
function error(_model, _resp, _options) {
|
||||
ok(model === _model);
|
||||
ok(resp === _resp);
|
||||
ok(options === _options);
|
||||
}
|
||||
});
|
||||
|
||||
test("#1179 - isValid returns true in the absence of validate.", 1, function() {
|
||||
var model = new Backbone.Model();
|
||||
model.validate = null;
|
||||
@@ -831,8 +805,9 @@ $(document).ready(function() {
|
||||
|
||||
test("#1412 - Trigger 'sync' event.", 3, function() {
|
||||
var model = new Backbone.Model({id: 1});
|
||||
model.sync = function(method, model, options) { options.success(); };
|
||||
model.on('sync', function() { ok(true); });
|
||||
model.url = '/test';
|
||||
model.on('sync', function(){ ok(true); });
|
||||
Backbone.ajax = function(settings){ settings.success(); };
|
||||
model.fetch();
|
||||
model.save();
|
||||
model.destroy();
|
||||
@@ -852,4 +827,66 @@ $(document).ready(function() {
|
||||
strictEqual(model.save(), false);
|
||||
});
|
||||
|
||||
test("#1377 - Save without attrs triggers 'error'.", 1, function() {
|
||||
var Model = Backbone.Model.extend({
|
||||
url: '/test/',
|
||||
sync: function(method, model, options){ options.success(); },
|
||||
validate: function(){ return 'invalid'; }
|
||||
});
|
||||
var model = new Model({id: 1});
|
||||
model.on('error', function(){ ok(true); });
|
||||
model.save();
|
||||
});
|
||||
|
||||
test("#1545 - `undefined` can be passed to a model constructor without coersion", function() {
|
||||
var Model = Backbone.Model.extend({
|
||||
defaults: { one: 1 },
|
||||
initialize : function(attrs, opts) {
|
||||
equal(attrs, undefined);
|
||||
}
|
||||
});
|
||||
var emptyattrs = new Model();
|
||||
var undefinedattrs = new Model(undefined);
|
||||
});
|
||||
|
||||
asyncTest("#1478 - Model `save` does not trigger change on unchanged attributes", 0, function() {
|
||||
var Model = Backbone.Model.extend({
|
||||
sync: function(method, model, options) {
|
||||
setTimeout(function(){
|
||||
options.success();
|
||||
start();
|
||||
}, 0);
|
||||
}
|
||||
});
|
||||
new Model({x: true})
|
||||
.on('change:x', function(){ ok(false); })
|
||||
.save(null, {wait: true});
|
||||
});
|
||||
|
||||
test("#1664 - Changing from one value, silently to another, back to original does not trigger change.", 0, function() {
|
||||
var model = new Backbone.Model({x:1});
|
||||
model.on('change:x', function() { ok(false); });
|
||||
model.set({x:2},{silent:true});
|
||||
model.set({x:3},{silent:true});
|
||||
model.set({x:1});
|
||||
});
|
||||
|
||||
test("#1664 - multiple silent changes nested inside a change event", 2, function() {
|
||||
var changes = [];
|
||||
var model = new Backbone.Model();
|
||||
model.on('change', function() {
|
||||
model.set({a:'c'}, {silent:true});
|
||||
model.set({b:2}, {silent:true});
|
||||
model.unset('c', {silent:true});
|
||||
model.set({a:'a'}, {silent:true});
|
||||
model.set({b:1}, {silent:true});
|
||||
model.set({c:'item'}, {silent:true});
|
||||
});
|
||||
model.on('change:a change:b change:c', function(model, val) { changes.push(val); });
|
||||
model.set({a:'a', b:1, c:'item'});
|
||||
deepEqual(changes, ['a',1,'item']);
|
||||
model.change();
|
||||
deepEqual(changes, ['a',1,'item']);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
2
vendor/backbone/test/noconflict.js
vendored
2
vendor/backbone/test/noconflict.js
vendored
@@ -2,7 +2,7 @@ $(document).ready(function() {
|
||||
|
||||
module("Backbone.noConflict");
|
||||
|
||||
test('Backbone.noConflict', 2, function() {
|
||||
test('noConflict', 2, function() {
|
||||
var noconflictBackbone = Backbone.noConflict();
|
||||
equal(window.Backbone, undefined, 'Returned window.Backbone');
|
||||
window.Backbone = noconflictBackbone;
|
||||
|
||||
194
vendor/backbone/test/router.js
vendored
194
vendor/backbone/test/router.js
vendored
@@ -41,7 +41,7 @@ $(document).ready(function() {
|
||||
|
||||
setup: function() {
|
||||
location = new Location('http://example.com');
|
||||
Backbone.history = new Backbone.History({location: location});
|
||||
Backbone.history = _.extend(new Backbone.History, {location: location});
|
||||
router = new Router({testing: 101});
|
||||
Backbone.history.interval = 9;
|
||||
Backbone.history.start({pushState: false});
|
||||
@@ -69,6 +69,7 @@ $(document).ready(function() {
|
||||
"contacts": "contacts",
|
||||
"contacts/new": "newContact",
|
||||
"contacts/:id": "loadContact",
|
||||
"optional(/:item)": "optionalItem",
|
||||
"splat/*args/end": "splat",
|
||||
"*first/complex-:part/*rest": "complex",
|
||||
":entity?*args": "query",
|
||||
@@ -105,6 +106,10 @@ $(document).ready(function() {
|
||||
this.contact = 'load';
|
||||
},
|
||||
|
||||
optionalItem: function(arg){
|
||||
this.arg = arg !== undefined ? arg : null;
|
||||
},
|
||||
|
||||
splat : function(args) {
|
||||
this.args = args;
|
||||
},
|
||||
@@ -126,11 +131,11 @@ $(document).ready(function() {
|
||||
|
||||
});
|
||||
|
||||
test("Router: initialize", 1, function() {
|
||||
test("initialize", 1, function() {
|
||||
equal(router.testing, 101);
|
||||
});
|
||||
|
||||
test("Router: routes (simple)", 4, function() {
|
||||
test("routes (simple)", 4, function() {
|
||||
location.replace('http://example.com#search/news');
|
||||
Backbone.history.checkUrl();
|
||||
equal(router.query, 'news');
|
||||
@@ -139,26 +144,26 @@ $(document).ready(function() {
|
||||
equal(lastArgs[0], 'news');
|
||||
});
|
||||
|
||||
test("Router: routes (two part)", 2, function() {
|
||||
test("routes (two part)", 2, function() {
|
||||
location.replace('http://example.com#search/nyc/p10');
|
||||
Backbone.history.checkUrl();
|
||||
equal(router.query, 'nyc');
|
||||
equal(router.page, '10');
|
||||
});
|
||||
|
||||
test("Router: routes via navigate", 2, function() {
|
||||
test("routes via navigate", 2, function() {
|
||||
Backbone.history.navigate('search/manhattan/p20', {trigger: true});
|
||||
equal(router.query, 'manhattan');
|
||||
equal(router.page, '20');
|
||||
});
|
||||
|
||||
test("Router: routes via navigate for backwards-compatibility", 2, function() {
|
||||
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("Router: route precedence via navigate", 6, function(){
|
||||
test("route precedence via navigate", 6, function(){
|
||||
// check both 0.9.x and backwards-compatibility options
|
||||
_.each([ { trigger: true }, true ], function( options ){
|
||||
Backbone.history.navigate('contacts', options);
|
||||
@@ -178,13 +183,13 @@ $(document).ready(function() {
|
||||
Backbone.history.navigate('/route');
|
||||
});
|
||||
|
||||
test("Router: use implicit callback if none provided", 1, function() {
|
||||
test("use implicit callback if none provided", 1, function() {
|
||||
router.count = 0;
|
||||
router.navigate('implicit', {trigger: true});
|
||||
equal(router.count, 1);
|
||||
});
|
||||
|
||||
test("Router: routes via navigate with {replace: true}", 1, function() {
|
||||
test("routes via navigate with {replace: true}", 1, function() {
|
||||
location.replace('http://example.com#start_here');
|
||||
Backbone.history.checkUrl();
|
||||
location.replace = function(href) {
|
||||
@@ -193,13 +198,22 @@ $(document).ready(function() {
|
||||
Backbone.history.navigate('end_here', {replace: true});
|
||||
});
|
||||
|
||||
test("Router: routes (splats)", 1, function() {
|
||||
test("routes (splats)", 1, function() {
|
||||
location.replace('http://example.com#splat/long-list/of/splatted_99args/end');
|
||||
Backbone.history.checkUrl();
|
||||
equal(router.args, 'long-list/of/splatted_99args');
|
||||
});
|
||||
|
||||
test("Router: routes (complex)", 3, function() {
|
||||
test("routes (optional)", 2, function() {
|
||||
location.replace('http://example.com#optional');
|
||||
Backbone.history.checkUrl();
|
||||
equal(router.arg, null);
|
||||
location.replace('http://example.com#optional/thing');
|
||||
Backbone.history.checkUrl();
|
||||
equal(router.arg, 'thing');
|
||||
});
|
||||
|
||||
test("routes (complex)", 3, function() {
|
||||
location.replace('http://example.com#one/two/three/complex-part/four/five/six/seven');
|
||||
Backbone.history.checkUrl();
|
||||
equal(router.first, 'one/two/three');
|
||||
@@ -207,7 +221,7 @@ $(document).ready(function() {
|
||||
equal(router.rest, 'four/five/six/seven');
|
||||
});
|
||||
|
||||
test("Router: routes (query)", 5, function() {
|
||||
test("routes (query)", 5, function() {
|
||||
location.replace('http://example.com#mandel?a=b&c=d');
|
||||
Backbone.history.checkUrl();
|
||||
equal(router.entity, 'mandel');
|
||||
@@ -217,13 +231,13 @@ $(document).ready(function() {
|
||||
equal(lastArgs[1], 'a=b&c=d');
|
||||
});
|
||||
|
||||
test("Router: routes (anything)", 1, function() {
|
||||
test("routes (anything)", 1, function() {
|
||||
location.replace('http://example.com#doesnt-match-a-route');
|
||||
Backbone.history.checkUrl();
|
||||
equal(router.anything, 'doesnt-match-a-route');
|
||||
});
|
||||
|
||||
test("Router: fires event when router doesn't have callback on it", 1, function() {
|
||||
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');
|
||||
Backbone.history.checkUrl();
|
||||
@@ -233,28 +247,25 @@ $(document).ready(function() {
|
||||
location.replace('http://example.com/root/foo');
|
||||
|
||||
Backbone.history.stop();
|
||||
Backbone.history = new Backbone.History({location: location});
|
||||
Backbone.history = _.extend(new Backbone.History, {location: location});
|
||||
Backbone.history.start({root: '/root', hashChange: false, silent: true});
|
||||
strictEqual(Backbone.history.getFragment(), 'foo');
|
||||
|
||||
Backbone.history.stop();
|
||||
Backbone.history = new Backbone.History({location: location});
|
||||
Backbone.history = _.extend(new Backbone.History, {location: location});
|
||||
Backbone.history.start({root: '/root/', hashChange: false, silent: true});
|
||||
strictEqual(Backbone.history.getFragment(), 'foo');
|
||||
});
|
||||
|
||||
test("#1003 - History is started before navigate is called", 1, function() {
|
||||
var history = new Backbone.History();
|
||||
history.navigate = function(){
|
||||
ok(Backbone.History.started);
|
||||
};
|
||||
Backbone.history.stop();
|
||||
history.start();
|
||||
Backbone.history.navigate = function(){ ok(Backbone.History.started); };
|
||||
Backbone.history.start();
|
||||
// If this is not an old IE navigate will not be called.
|
||||
if (!history.iframe) ok(true);
|
||||
if (!Backbone.history.iframe) ok(true);
|
||||
});
|
||||
|
||||
test("Router: route callback gets passed decoded values", 3, function() {
|
||||
test("route callback gets passed decoded values", 3, function() {
|
||||
var route = 'has%2Fslash/complex-has%23hash/has%20space';
|
||||
Backbone.history.navigate(route, {trigger: true});
|
||||
equal(router.first, 'has/slash');
|
||||
@@ -262,7 +273,7 @@ $(document).ready(function() {
|
||||
equal(router.rest, 'has space');
|
||||
});
|
||||
|
||||
test("Router: correctly handles URLs with % (#868)", 3, function() {
|
||||
test("correctly handles URLs with % (#868)", 3, function() {
|
||||
location.replace('http://example.com#search/fat%3A1.5%25');
|
||||
Backbone.history.checkUrl();
|
||||
location.replace('http://example.com#search/fat');
|
||||
@@ -275,7 +286,7 @@ $(document).ready(function() {
|
||||
test("#1185 - Use pathname when hashChange is not wanted.", 1, function() {
|
||||
Backbone.history.stop();
|
||||
location.replace('http://example.com/path/name#hash');
|
||||
Backbone.history = new Backbone.History({location: location});
|
||||
Backbone.history = _.extend(new Backbone.History, {location: location});
|
||||
Backbone.history.start({hashChange: false});
|
||||
var fragment = Backbone.history.getFragment();
|
||||
strictEqual(fragment, location.pathname.replace(/^\//, ''));
|
||||
@@ -284,7 +295,7 @@ $(document).ready(function() {
|
||||
test("#1206 - Strip leading slash before location.assign.", 1, function() {
|
||||
Backbone.history.stop();
|
||||
location.replace('http://example.com/root/');
|
||||
Backbone.history = new Backbone.History({location: location});
|
||||
Backbone.history = _.extend(new Backbone.History, {location: location});
|
||||
Backbone.history.start({hashChange: false, root: '/root/'});
|
||||
location.assign = function(pathname) {
|
||||
strictEqual(pathname, '/root/fragment');
|
||||
@@ -295,7 +306,7 @@ $(document).ready(function() {
|
||||
test("#1387 - Root fragment without trailing slash.", 1, function() {
|
||||
Backbone.history.stop();
|
||||
location.replace('http://example.com/root');
|
||||
Backbone.history = new Backbone.History({location: location});
|
||||
Backbone.history = _.extend(new Backbone.History, {location: location});
|
||||
Backbone.history.start({hashChange: false, root: '/root/', silent: true});
|
||||
strictEqual(Backbone.history.getFragment(), '');
|
||||
});
|
||||
@@ -303,7 +314,7 @@ $(document).ready(function() {
|
||||
test("#1366 - History does not prepend root to fragment.", 2, function() {
|
||||
Backbone.history.stop();
|
||||
location.replace('http://example.com/root/');
|
||||
Backbone.history = new Backbone.History({
|
||||
Backbone.history = _.extend(new Backbone.History, {
|
||||
location: location,
|
||||
history: {
|
||||
pushState: function(state, title, url) {
|
||||
@@ -320,10 +331,10 @@ $(document).ready(function() {
|
||||
strictEqual(Backbone.history.fragment, 'x');
|
||||
});
|
||||
|
||||
test("Router: Normalize root.", 1, function() {
|
||||
test("Normalize root.", 1, function() {
|
||||
Backbone.history.stop();
|
||||
location.replace('http://example.com/root');
|
||||
Backbone.history = new Backbone.History({
|
||||
Backbone.history = _.extend(new Backbone.History, {
|
||||
location: location,
|
||||
history: {
|
||||
pushState: function(state, title, url) {
|
||||
@@ -339,15 +350,15 @@ $(document).ready(function() {
|
||||
Backbone.history.navigate('fragment');
|
||||
});
|
||||
|
||||
test("Router: Normalize root.", 1, function() {
|
||||
test("Normalize root.", 1, function() {
|
||||
Backbone.history.stop();
|
||||
location.replace('http://example.com/root#fragment');
|
||||
Backbone.history = new Backbone.History({
|
||||
Backbone.history = _.extend(new Backbone.History, {
|
||||
location: location,
|
||||
history: {
|
||||
pushState: function(state, title, url) {},
|
||||
replaceState: function(state, title, url) {
|
||||
strictEqual(url, 'http://example.com/root/fragment');
|
||||
strictEqual(url, '/root/fragment');
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -357,10 +368,10 @@ $(document).ready(function() {
|
||||
});
|
||||
});
|
||||
|
||||
test("Router: Normalize root.", 1, function() {
|
||||
test("Normalize root.", 1, function() {
|
||||
Backbone.history.stop();
|
||||
location.replace('http://example.com/root');
|
||||
Backbone.history = new Backbone.History({location: location});
|
||||
Backbone.history = _.extend(new Backbone.History, {location: location});
|
||||
Backbone.history.loadUrl = function() { ok(true); };
|
||||
Backbone.history.start({
|
||||
pushState: true,
|
||||
@@ -368,4 +379,117 @@ $(document).ready(function() {
|
||||
});
|
||||
});
|
||||
|
||||
test("Normalize root - leading slash.", 1, function() {
|
||||
Backbone.history.stop();
|
||||
location.replace('http://example.com/root');
|
||||
Backbone.history = _.extend(new Backbone.History, {
|
||||
location: location,
|
||||
history: {
|
||||
pushState: function(){},
|
||||
replaceState: function(){}
|
||||
}
|
||||
});
|
||||
Backbone.history.start({root: 'root'});
|
||||
strictEqual(Backbone.history.root, '/root/');
|
||||
});
|
||||
|
||||
test("Transition from hashChange to pushState.", 1, function() {
|
||||
Backbone.history.stop();
|
||||
location.replace('http://example.com/root#x/y');
|
||||
Backbone.history = _.extend(new Backbone.History, {
|
||||
location: location,
|
||||
history: {
|
||||
pushState: function(){},
|
||||
replaceState: function(state, title, url){
|
||||
strictEqual(url, '/root/x/y');
|
||||
}
|
||||
}
|
||||
});
|
||||
Backbone.history.start({
|
||||
root: 'root',
|
||||
pushState: true
|
||||
});
|
||||
});
|
||||
|
||||
test("#1619: Router: Normalize empty root", 1, function() {
|
||||
Backbone.history.stop();
|
||||
location.replace('http://example.com/');
|
||||
Backbone.history = _.extend(new Backbone.History, {
|
||||
location: location,
|
||||
history: {
|
||||
pushState: function(){},
|
||||
replaceState: function(){}
|
||||
}
|
||||
});
|
||||
Backbone.history.start({root: ''});
|
||||
strictEqual(Backbone.history.root, '/');
|
||||
});
|
||||
|
||||
test("#1619: Router: nagivate with empty root", 1, function() {
|
||||
Backbone.history.stop();
|
||||
location.replace('http://example.com/');
|
||||
Backbone.history = _.extend(new Backbone.History, {
|
||||
location: location,
|
||||
history: {
|
||||
pushState: function(state, title, url) {
|
||||
strictEqual(url, '/fragment');
|
||||
}
|
||||
}
|
||||
});
|
||||
Backbone.history.start({
|
||||
pushState: true,
|
||||
root: '',
|
||||
hashChange: false
|
||||
});
|
||||
Backbone.history.navigate('fragment');
|
||||
});
|
||||
|
||||
test("Transition from pushState to hashChange.", 1, function() {
|
||||
Backbone.history.stop();
|
||||
location.replace('http://example.com/root/x/y?a=b');
|
||||
location.replace = function(url) {
|
||||
strictEqual(url, '/root/?a=b#x/y');
|
||||
};
|
||||
Backbone.history = _.extend(new Backbone.History, {
|
||||
location: location,
|
||||
history: {
|
||||
pushState: null,
|
||||
replaceState: null
|
||||
}
|
||||
});
|
||||
Backbone.history.start({
|
||||
root: 'root',
|
||||
pushState: true
|
||||
});
|
||||
});
|
||||
|
||||
test("#1695 - hashChange to pushState with search.", 1, 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(state, title, url){
|
||||
strictEqual(url, '/root/x/y?a=b');
|
||||
}
|
||||
}
|
||||
});
|
||||
Backbone.history.start({
|
||||
root: 'root',
|
||||
pushState: true
|
||||
});
|
||||
});
|
||||
|
||||
test("#1746 - Router allows empty route.", 1, function() {
|
||||
var Router = Backbone.Router.extend({
|
||||
routes: {'': 'empty'},
|
||||
empty: function(){},
|
||||
route: function(route){
|
||||
strictEqual(route, '');
|
||||
}
|
||||
});
|
||||
new Router;
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
142
vendor/backbone/test/sync.js
vendored
142
vendor/backbone/test/sync.js
vendored
@@ -1,8 +1,5 @@
|
||||
$(document).ready(function() {
|
||||
|
||||
var ajax = Backbone.ajax;
|
||||
var lastRequest = null;
|
||||
|
||||
var Library = Backbone.Collection.extend({
|
||||
url : function() { return '/library'; }
|
||||
});
|
||||
@@ -14,132 +11,131 @@ $(document).ready(function() {
|
||||
length : 123
|
||||
};
|
||||
|
||||
module("Backbone.sync", {
|
||||
module("Backbone.sync", _.extend(new Environment, {
|
||||
|
||||
setup : function() {
|
||||
library = new Library();
|
||||
Backbone.ajax = function(obj) {
|
||||
lastRequest = obj;
|
||||
};
|
||||
Environment.prototype.setup.apply(this, arguments);
|
||||
library = new Library;
|
||||
library.create(attrs, {wait: false});
|
||||
},
|
||||
|
||||
teardown: function() {
|
||||
Backbone.ajax = ajax;
|
||||
Environment.prototype.teardown.apply(this, arguments);
|
||||
Backbone.emulateHTTP = false;
|
||||
}
|
||||
|
||||
});
|
||||
}));
|
||||
|
||||
test("sync: read", 4, function() {
|
||||
test("read", 4, function() {
|
||||
library.fetch();
|
||||
equal(lastRequest.url, '/library');
|
||||
equal(lastRequest.type, 'GET');
|
||||
equal(lastRequest.dataType, 'json');
|
||||
ok(_.isEmpty(lastRequest.data));
|
||||
equal(this.ajaxSettings.url, '/library');
|
||||
equal(this.ajaxSettings.type, 'GET');
|
||||
equal(this.ajaxSettings.dataType, 'json');
|
||||
ok(_.isEmpty(this.ajaxSettings.data));
|
||||
});
|
||||
|
||||
test("sync: passing data", 3, function() {
|
||||
test("passing data", 3, function() {
|
||||
library.fetch({data: {a: 'a', one: 1}});
|
||||
equal(lastRequest.url, '/library');
|
||||
equal(lastRequest.data.a, 'a');
|
||||
equal(lastRequest.data.one, 1);
|
||||
equal(this.ajaxSettings.url, '/library');
|
||||
equal(this.ajaxSettings.data.a, 'a');
|
||||
equal(this.ajaxSettings.data.one, 1);
|
||||
});
|
||||
|
||||
test("sync: create", 6, function() {
|
||||
equal(lastRequest.url, '/library');
|
||||
equal(lastRequest.type, 'POST');
|
||||
equal(lastRequest.dataType, 'json');
|
||||
var data = JSON.parse(lastRequest.data);
|
||||
test("create", 6, function() {
|
||||
equal(this.ajaxSettings.url, '/library');
|
||||
equal(this.ajaxSettings.type, 'POST');
|
||||
equal(this.ajaxSettings.dataType, 'json');
|
||||
var data = JSON.parse(this.ajaxSettings.data);
|
||||
equal(data.title, 'The Tempest');
|
||||
equal(data.author, 'Bill Shakespeare');
|
||||
equal(data.length, 123);
|
||||
});
|
||||
|
||||
test("sync: update", 7, function() {
|
||||
test("update", 7, function() {
|
||||
library.first().save({id: '1-the-tempest', author: 'William Shakespeare'});
|
||||
equal(lastRequest.url, '/library/1-the-tempest');
|
||||
equal(lastRequest.type, 'PUT');
|
||||
equal(lastRequest.dataType, 'json');
|
||||
var data = JSON.parse(lastRequest.data);
|
||||
equal(this.ajaxSettings.url, '/library/1-the-tempest');
|
||||
equal(this.ajaxSettings.type, 'PUT');
|
||||
equal(this.ajaxSettings.dataType, 'json');
|
||||
var data = JSON.parse(this.ajaxSettings.data);
|
||||
equal(data.id, '1-the-tempest');
|
||||
equal(data.title, 'The Tempest');
|
||||
equal(data.author, 'William Shakespeare');
|
||||
equal(data.length, 123);
|
||||
});
|
||||
|
||||
test("sync: update with emulateHTTP and emulateJSON", 7, function() {
|
||||
test("update with emulateHTTP and emulateJSON", 7, function() {
|
||||
Backbone.emulateHTTP = Backbone.emulateJSON = true;
|
||||
library.first().save({id: '2-the-tempest', author: 'Tim Shakespeare'});
|
||||
equal(lastRequest.url, '/library/2-the-tempest');
|
||||
equal(lastRequest.type, 'POST');
|
||||
equal(lastRequest.dataType, 'json');
|
||||
equal(lastRequest.data._method, 'PUT');
|
||||
var data = JSON.parse(lastRequest.data.model);
|
||||
equal(this.ajaxSettings.url, '/library/2-the-tempest');
|
||||
equal(this.ajaxSettings.type, 'POST');
|
||||
equal(this.ajaxSettings.dataType, 'json');
|
||||
equal(this.ajaxSettings.data._method, 'PUT');
|
||||
var data = JSON.parse(this.ajaxSettings.data.model);
|
||||
equal(data.id, '2-the-tempest');
|
||||
equal(data.author, 'Tim Shakespeare');
|
||||
equal(data.length, 123);
|
||||
Backbone.emulateHTTP = Backbone.emulateJSON = false;
|
||||
});
|
||||
|
||||
test("sync: update with just emulateHTTP", 6, function() {
|
||||
test("update with just emulateHTTP", 6, function() {
|
||||
Backbone.emulateHTTP = true;
|
||||
library.first().save({id: '2-the-tempest', author: 'Tim Shakespeare'});
|
||||
equal(lastRequest.url, '/library/2-the-tempest');
|
||||
equal(lastRequest.type, 'POST');
|
||||
equal(lastRequest.contentType, 'application/json');
|
||||
var data = JSON.parse(lastRequest.data);
|
||||
equal(this.ajaxSettings.url, '/library/2-the-tempest');
|
||||
equal(this.ajaxSettings.type, 'POST');
|
||||
equal(this.ajaxSettings.contentType, 'application/json');
|
||||
var data = JSON.parse(this.ajaxSettings.data);
|
||||
equal(data.id, '2-the-tempest');
|
||||
equal(data.author, 'Tim Shakespeare');
|
||||
equal(data.length, 123);
|
||||
Backbone.emulateHTTP = false;
|
||||
});
|
||||
|
||||
test("sync: update with just emulateJSON", 6, function() {
|
||||
test("update with just emulateJSON", 6, function() {
|
||||
Backbone.emulateJSON = true;
|
||||
library.first().save({id: '2-the-tempest', author: 'Tim Shakespeare'});
|
||||
equal(lastRequest.url, '/library/2-the-tempest');
|
||||
equal(lastRequest.type, 'PUT');
|
||||
equal(lastRequest.contentType, 'application/x-www-form-urlencoded');
|
||||
var data = JSON.parse(lastRequest.data.model);
|
||||
equal(this.ajaxSettings.url, '/library/2-the-tempest');
|
||||
equal(this.ajaxSettings.type, 'PUT');
|
||||
equal(this.ajaxSettings.contentType, 'application/x-www-form-urlencoded');
|
||||
var data = JSON.parse(this.ajaxSettings.data.model);
|
||||
equal(data.id, '2-the-tempest');
|
||||
equal(data.author, 'Tim Shakespeare');
|
||||
equal(data.length, 123);
|
||||
Backbone.emulateJSON = false;
|
||||
});
|
||||
|
||||
test("sync: read model", 3, function() {
|
||||
test("read model", 3, function() {
|
||||
library.first().save({id: '2-the-tempest', author: 'Tim Shakespeare'});
|
||||
library.first().fetch();
|
||||
equal(lastRequest.url, '/library/2-the-tempest');
|
||||
equal(lastRequest.type, 'GET');
|
||||
ok(_.isEmpty(lastRequest.data));
|
||||
equal(this.ajaxSettings.url, '/library/2-the-tempest');
|
||||
equal(this.ajaxSettings.type, 'GET');
|
||||
ok(_.isEmpty(this.ajaxSettings.data));
|
||||
});
|
||||
|
||||
test("sync: destroy", 3, function() {
|
||||
test("destroy", 3, function() {
|
||||
library.first().save({id: '2-the-tempest', author: 'Tim Shakespeare'});
|
||||
library.first().destroy({wait: true});
|
||||
equal(lastRequest.url, '/library/2-the-tempest');
|
||||
equal(lastRequest.type, 'DELETE');
|
||||
equal(lastRequest.data, null);
|
||||
equal(this.ajaxSettings.url, '/library/2-the-tempest');
|
||||
equal(this.ajaxSettings.type, 'DELETE');
|
||||
equal(this.ajaxSettings.data, null);
|
||||
});
|
||||
|
||||
test("sync: destroy with emulateHTTP", 3, function() {
|
||||
test("destroy with emulateHTTP", 3, function() {
|
||||
library.first().save({id: '2-the-tempest', author: 'Tim Shakespeare'});
|
||||
Backbone.emulateHTTP = Backbone.emulateJSON = true;
|
||||
library.first().destroy();
|
||||
equal(lastRequest.url, '/library/2-the-tempest');
|
||||
equal(lastRequest.type, 'POST');
|
||||
equal(JSON.stringify(lastRequest.data), '{"_method":"DELETE"}');
|
||||
equal(this.ajaxSettings.url, '/library/2-the-tempest');
|
||||
equal(this.ajaxSettings.type, 'POST');
|
||||
equal(JSON.stringify(this.ajaxSettings.data), '{"_method":"DELETE"}');
|
||||
Backbone.emulateHTTP = Backbone.emulateJSON = false;
|
||||
});
|
||||
|
||||
test("sync: urlError", 2, function() {
|
||||
test("urlError", 2, function() {
|
||||
var model = new Backbone.Model();
|
||||
raises(function() {
|
||||
model.fetch();
|
||||
});
|
||||
model.fetch({url: '/one/two'});
|
||||
equal(lastRequest.url, '/one/two');
|
||||
equal(this.ajaxSettings.url, '/one/two');
|
||||
});
|
||||
|
||||
test("#1052 - `options` is optional.", 0, function() {
|
||||
@@ -157,4 +153,32 @@ $(document).ready(function() {
|
||||
Backbone.sync('create', model);
|
||||
});
|
||||
|
||||
test("Call provided error callback on error.", 1, function() {
|
||||
var model = new Backbone.Model;
|
||||
model.url = '/test';
|
||||
Backbone.sync('read', model, {
|
||||
error: function() { ok(true); }
|
||||
});
|
||||
this.ajaxSettings.error();
|
||||
});
|
||||
|
||||
test("#1756 - Call user provided beforeSend function.", 4, function() {
|
||||
Backbone.emulateHTTP = true;
|
||||
var model = new Backbone.Model;
|
||||
model.url = '/test';
|
||||
var xhr = {
|
||||
setRequestHeader: function(header, value) {
|
||||
strictEqual(header, 'X-HTTP-Method-Override');
|
||||
strictEqual(value, 'DELETE');
|
||||
}
|
||||
};
|
||||
model.sync('delete', model, {
|
||||
beforeSend: function(_xhr) {
|
||||
ok(_xhr === xhr);
|
||||
return false;
|
||||
}
|
||||
});
|
||||
strictEqual(this.ajaxSettings.beforeSend(xhr), false);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
9266
vendor/backbone/test/vendor/jquery-1.7.1.js
vendored
9266
vendor/backbone/test/vendor/jquery-1.7.1.js
vendored
File diff suppressed because it is too large
Load Diff
649
vendor/backbone/test/vendor/jslitmus.js
vendored
649
vendor/backbone/test/vendor/jslitmus.js
vendored
@@ -1,649 +0,0 @@
|
||||
// JSLitmus.js
|
||||
//
|
||||
// Copyright (c) 2010, Robert Kieffer, http://broofa.com
|
||||
// Available under MIT license (http://en.wikipedia.org/wiki/MIT_License)
|
||||
|
||||
(function() {
|
||||
// Private methods and state
|
||||
|
||||
// Get platform info but don't go crazy trying to recognize everything
|
||||
// that's out there. This is just for the major platforms and OSes.
|
||||
var platform = 'unknown platform', ua = navigator.userAgent;
|
||||
|
||||
// Detect OS
|
||||
var oses = ['Windows','iPhone OS','(Intel |PPC )?Mac OS X','Linux'].join('|');
|
||||
var pOS = new RegExp('((' + oses + ') [^ \);]*)').test(ua) ? RegExp.$1 : null;
|
||||
if (!pOS) pOS = new RegExp('((' + oses + ')[^ \);]*)').test(ua) ? RegExp.$1 : null;
|
||||
|
||||
// Detect browser
|
||||
var pName = /(Chrome|MSIE|Safari|Opera|Firefox)/.test(ua) ? RegExp.$1 : null;
|
||||
|
||||
// Detect version
|
||||
var vre = new RegExp('(Version|' + pName + ')[ \/]([^ ;]*)');
|
||||
var pVersion = (pName && vre.test(ua)) ? RegExp.$2 : null;
|
||||
var platform = (pOS && pName && pVersion) ? pName + ' ' + pVersion + ' on ' + pOS : 'unknown platform';
|
||||
|
||||
/**
|
||||
* A smattering of methods that are needed to implement the JSLitmus testbed.
|
||||
*/
|
||||
var jsl = {
|
||||
/**
|
||||
* Enhanced version of escape()
|
||||
*/
|
||||
escape: function(s) {
|
||||
s = s.replace(/,/g, '\\,');
|
||||
s = escape(s);
|
||||
s = s.replace(/\+/g, '%2b');
|
||||
s = s.replace(/ /g, '+');
|
||||
return s;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get an element by ID.
|
||||
*/
|
||||
$: function(id) {
|
||||
return document.getElementById(id);
|
||||
},
|
||||
|
||||
/**
|
||||
* Null function
|
||||
*/
|
||||
F: function() {},
|
||||
|
||||
/**
|
||||
* Set the status shown in the UI
|
||||
*/
|
||||
status: function(msg) {
|
||||
var el = jsl.$('jsl_status');
|
||||
if (el) el.innerHTML = msg || '';
|
||||
},
|
||||
|
||||
/**
|
||||
* Convert a number to an abbreviated string like, "15K" or "10M"
|
||||
*/
|
||||
toLabel: function(n) {
|
||||
if (n == Infinity) {
|
||||
return 'Infinity';
|
||||
} else if (n > 1e9) {
|
||||
n = Math.round(n/1e8);
|
||||
return n/10 + 'B';
|
||||
} else if (n > 1e6) {
|
||||
n = Math.round(n/1e5);
|
||||
return n/10 + 'M';
|
||||
} else if (n > 1e3) {
|
||||
n = Math.round(n/1e2);
|
||||
return n/10 + 'K';
|
||||
}
|
||||
return n;
|
||||
},
|
||||
|
||||
/**
|
||||
* Copy properties from src to dst
|
||||
*/
|
||||
extend: function(dst, src) {
|
||||
for (var k in src) dst[k] = src[k]; return dst;
|
||||
},
|
||||
|
||||
/**
|
||||
* Like Array.join(), but for the key-value pairs in an object
|
||||
*/
|
||||
join: function(o, delimit1, delimit2) {
|
||||
if (o.join) return o.join(delimit1); // If it's an array
|
||||
var pairs = [];
|
||||
for (var k in o) pairs.push(k + delimit1 + o[k]);
|
||||
return pairs.join(delimit2);
|
||||
},
|
||||
|
||||
/**
|
||||
* Array#indexOf isn't supported in IE, so we use this as a cross-browser solution
|
||||
*/
|
||||
indexOf: function(arr, o) {
|
||||
if (arr.indexOf) return arr.indexOf(o);
|
||||
for (var i = 0; i < this.length; i++) if (arr[i] === o) return i;
|
||||
return -1;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Test manages a single test (created with
|
||||
* JSLitmus.test())
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
var Test = function (name, f) {
|
||||
if (!f) throw new Error('Undefined test function');
|
||||
if (!/function[^\(]*\(([^,\)]*)/.test(f.toString())) {
|
||||
throw new Error('"' + name + '" test: Test is not a valid Function object');
|
||||
}
|
||||
this.loopArg = RegExp.$1;
|
||||
this.name = name;
|
||||
this.f = f;
|
||||
};
|
||||
|
||||
jsl.extend(Test, /** @lends Test */ {
|
||||
/** Calibration tests for establishing iteration loop overhead */
|
||||
CALIBRATIONS: [
|
||||
new Test('calibrating loop', function(count) {while (count--);}),
|
||||
new Test('calibrating function', jsl.F)
|
||||
],
|
||||
|
||||
/**
|
||||
* Run calibration tests. Returns true if calibrations are not yet
|
||||
* complete (in which case calling code should run the tests yet again).
|
||||
* onCalibrated - Callback to invoke when calibrations have finished
|
||||
*/
|
||||
calibrate: function(onCalibrated) {
|
||||
for (var i = 0; i < Test.CALIBRATIONS.length; i++) {
|
||||
var cal = Test.CALIBRATIONS[i];
|
||||
if (cal.running) return true;
|
||||
if (!cal.count) {
|
||||
cal.isCalibration = true;
|
||||
cal.onStop = onCalibrated;
|
||||
//cal.MIN_TIME = .1; // Do calibrations quickly
|
||||
cal.run(2e4);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
jsl.extend(Test.prototype, {/** @lends Test.prototype */
|
||||
/** Initial number of iterations */
|
||||
INIT_COUNT: 10,
|
||||
/** Max iterations allowed (i.e. used to detect bad looping functions) */
|
||||
MAX_COUNT: 1e9,
|
||||
/** Minimum time a test should take to get valid results (secs) */
|
||||
MIN_TIME: .5,
|
||||
|
||||
/** Callback invoked when test state changes */
|
||||
onChange: jsl.F,
|
||||
|
||||
/** Callback invoked when test is finished */
|
||||
onStop: jsl.F,
|
||||
|
||||
/**
|
||||
* Reset test state
|
||||
*/
|
||||
reset: function() {
|
||||
delete this.count;
|
||||
delete this.time;
|
||||
delete this.running;
|
||||
delete this.error;
|
||||
},
|
||||
|
||||
/**
|
||||
* Run the test (in a timeout). We use a timeout to make sure the browser
|
||||
* has a chance to finish rendering any UI changes we've made, like
|
||||
* updating the status message.
|
||||
*/
|
||||
run: function(count) {
|
||||
count = count || this.INIT_COUNT;
|
||||
jsl.status(this.name + ' x ' + count);
|
||||
this.running = true;
|
||||
var me = this;
|
||||
setTimeout(function() {me._run(count);}, 200);
|
||||
},
|
||||
|
||||
/**
|
||||
* The nuts and bolts code that actually runs a test
|
||||
*/
|
||||
_run: function(count) {
|
||||
var me = this;
|
||||
|
||||
// Make sure calibration tests have run
|
||||
if (!me.isCalibration && Test.calibrate(function() {me.run(count);})) return;
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
var start, f = this.f, now, i = count;
|
||||
|
||||
// Start the timer
|
||||
start = new Date();
|
||||
|
||||
// Now for the money shot. If this is a looping function ...
|
||||
if (this.loopArg) {
|
||||
// ... let it do the iteration itself
|
||||
f(count);
|
||||
} else {
|
||||
// ... otherwise do the iteration for it
|
||||
while (i--) f();
|
||||
}
|
||||
|
||||
// Get time test took (in secs)
|
||||
this.time = Math.max(1,new Date() - start)/1000;
|
||||
|
||||
// Store iteration count and per-operation time taken
|
||||
this.count = count;
|
||||
this.period = this.time/count;
|
||||
|
||||
// Do we need to do another run?
|
||||
this.running = this.time <= this.MIN_TIME;
|
||||
|
||||
// ... if so, compute how many times we should iterate
|
||||
if (this.running) {
|
||||
// Bump the count to the nearest power of 2
|
||||
var x = this.MIN_TIME/this.time;
|
||||
var pow = Math.pow(2, Math.max(1, Math.ceil(Math.log(x)/Math.log(2))));
|
||||
count *= pow;
|
||||
if (count > this.MAX_COUNT) {
|
||||
throw new Error('Max count exceeded. If this test uses a looping function, make sure the iteration loop is working properly.');
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// Exceptions are caught and displayed in the test UI
|
||||
this.reset();
|
||||
this.error = e;
|
||||
}
|
||||
|
||||
// Figure out what to do next
|
||||
if (this.running) {
|
||||
me.run(count);
|
||||
} else {
|
||||
jsl.status('');
|
||||
me.onStop(me);
|
||||
}
|
||||
|
||||
// Finish up
|
||||
this.onChange(this);
|
||||
},
|
||||
|
||||
/**
|
||||
* Get the number of operations per second for this test.
|
||||
*
|
||||
* @param normalize if true, iteration loop overhead taken into account
|
||||
*/
|
||||
getHz: function(/**Boolean*/ normalize) {
|
||||
var p = this.period;
|
||||
|
||||
// Adjust period based on the calibration test time
|
||||
if (normalize && !this.isCalibration) {
|
||||
var cal = Test.CALIBRATIONS[this.loopArg ? 0 : 1];
|
||||
|
||||
// If the period is within 20% of the calibration time, then zero the
|
||||
// it out
|
||||
p = p < cal.period*1.2 ? 0 : p - cal.period;
|
||||
}
|
||||
|
||||
return Math.round(1/p);
|
||||
},
|
||||
|
||||
/**
|
||||
* Get a friendly string describing the test
|
||||
*/
|
||||
toString: function() {
|
||||
return this.name + ' - ' + this.time/this.count + ' secs';
|
||||
}
|
||||
});
|
||||
|
||||
// CSS we need for the UI
|
||||
var STYLESHEET = '<style> \
|
||||
#jslitmus {font-family:sans-serif; font-size: 12px;} \
|
||||
#jslitmus a {text-decoration: none;} \
|
||||
#jslitmus a:hover {text-decoration: underline;} \
|
||||
#jsl_status { \
|
||||
margin-top: 10px; \
|
||||
font-size: 10px; \
|
||||
color: #888; \
|
||||
} \
|
||||
A IMG {border:none} \
|
||||
#test_results { \
|
||||
margin-top: 10px; \
|
||||
font-size: 12px; \
|
||||
font-family: sans-serif; \
|
||||
border-collapse: collapse; \
|
||||
border-spacing: 0px; \
|
||||
} \
|
||||
#test_results th, #test_results td { \
|
||||
border: solid 1px #ccc; \
|
||||
vertical-align: top; \
|
||||
padding: 3px; \
|
||||
} \
|
||||
#test_results th { \
|
||||
vertical-align: bottom; \
|
||||
background-color: #ccc; \
|
||||
padding: 1px; \
|
||||
font-size: 10px; \
|
||||
} \
|
||||
#test_results #test_platform { \
|
||||
color: #444; \
|
||||
text-align:center; \
|
||||
} \
|
||||
#test_results .test_row { \
|
||||
color: #006; \
|
||||
cursor: pointer; \
|
||||
} \
|
||||
#test_results .test_nonlooping { \
|
||||
border-left-style: dotted; \
|
||||
border-left-width: 2px; \
|
||||
} \
|
||||
#test_results .test_looping { \
|
||||
border-left-style: solid; \
|
||||
border-left-width: 2px; \
|
||||
} \
|
||||
#test_results .test_name {white-space: nowrap;} \
|
||||
#test_results .test_pending { \
|
||||
} \
|
||||
#test_results .test_running { \
|
||||
font-style: italic; \
|
||||
} \
|
||||
#test_results .test_done {} \
|
||||
#test_results .test_done { \
|
||||
text-align: right; \
|
||||
font-family: monospace; \
|
||||
} \
|
||||
#test_results .test_error {color: #600;} \
|
||||
#test_results .test_error .error_head {font-weight:bold;} \
|
||||
#test_results .test_error .error_body {font-size:85%;} \
|
||||
#test_results .test_row:hover td { \
|
||||
background-color: #ffc; \
|
||||
text-decoration: underline; \
|
||||
} \
|
||||
#chart { \
|
||||
margin: 10px 0px; \
|
||||
width: 250px; \
|
||||
} \
|
||||
#chart img { \
|
||||
border: solid 1px #ccc; \
|
||||
margin-bottom: 5px; \
|
||||
} \
|
||||
#chart #tiny_url { \
|
||||
height: 40px; \
|
||||
width: 250px; \
|
||||
} \
|
||||
#jslitmus_credit { \
|
||||
font-size: 10px; \
|
||||
color: #888; \
|
||||
margin-top: 8px; \
|
||||
} \
|
||||
</style>';
|
||||
|
||||
// HTML markup for the UI
|
||||
var MARKUP = '<div id="jslitmus"> \
|
||||
<button onclick="JSLitmus.runAll(event)">Run Tests</button> \
|
||||
<button id="stop_button" disabled="disabled" onclick="JSLitmus.stop()">Stop Tests</button> \
|
||||
<br \> \
|
||||
<br \> \
|
||||
<input type="checkbox" style="vertical-align: middle" id="test_normalize" checked="checked" onchange="JSLitmus.renderAll()""> Normalize results \
|
||||
<table id="test_results"> \
|
||||
<colgroup> \
|
||||
<col /> \
|
||||
<col width="100" /> \
|
||||
</colgroup> \
|
||||
<tr><th id="test_platform" colspan="2">' + platform + '</th></tr> \
|
||||
<tr><th>Test</th><th>Ops/sec</th></tr> \
|
||||
<tr id="test_row_template" class="test_row" style="display:none"> \
|
||||
<td class="test_name"></td> \
|
||||
<td class="test_result">Ready</td> \
|
||||
</tr> \
|
||||
</table> \
|
||||
<div id="jsl_status"></div> \
|
||||
<div id="chart" style="display:none"> \
|
||||
<a id="chart_link" target="_blank"><img id="chart_image"></a> \
|
||||
TinyURL (for chart): \
|
||||
<iframe id="tiny_url" frameBorder="0" scrolling="no" src=""></iframe> \
|
||||
</div> \
|
||||
<a id="jslitmus_credit" title="JSLitmus home page" href="http://code.google.com/p/jslitmus" target="_blank">Powered by JSLitmus</a> \
|
||||
</div>';
|
||||
|
||||
/**
|
||||
* The public API for creating and running tests
|
||||
*/
|
||||
window.JSLitmus = {
|
||||
/** The list of all tests that have been registered with JSLitmus.test */
|
||||
_tests: [],
|
||||
/** The queue of tests that need to be run */
|
||||
_queue: [],
|
||||
|
||||
/**
|
||||
* The parsed query parameters the current page URL. This is provided as a
|
||||
* convenience for test functions - it's not used by JSLitmus proper
|
||||
*/
|
||||
params: {},
|
||||
|
||||
/**
|
||||
* Initialize
|
||||
*/
|
||||
_init: function() {
|
||||
// Parse query params into JSLitmus.params[] hash
|
||||
var match = (location + '').match(/([^?#]*)(#.*)?$/);
|
||||
if (match) {
|
||||
var pairs = match[1].split('&');
|
||||
for (var i = 0; i < pairs.length; i++) {
|
||||
var pair = pairs[i].split('=');
|
||||
if (pair.length > 1) {
|
||||
var key = pair.shift();
|
||||
var value = pair.length > 1 ? pair.join('=') : pair[0];
|
||||
this.params[key] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Write out the stylesheet. We have to do this here because IE
|
||||
// doesn't honor sheets written after the document has loaded.
|
||||
document.write(STYLESHEET);
|
||||
|
||||
// Setup the rest of the UI once the document is loaded
|
||||
if (window.addEventListener) {
|
||||
window.addEventListener('load', this._setup, false);
|
||||
} else if (document.addEventListener) {
|
||||
document.addEventListener('load', this._setup, false);
|
||||
} else if (window.attachEvent) {
|
||||
window.attachEvent('onload', this._setup);
|
||||
}
|
||||
|
||||
return this;
|
||||
},
|
||||
|
||||
/**
|
||||
* Set up the UI
|
||||
*/
|
||||
_setup: function() {
|
||||
var el = jsl.$('jslitmus_container');
|
||||
if (!el) document.body.appendChild(el = document.createElement('div'));
|
||||
|
||||
el.innerHTML = MARKUP;
|
||||
|
||||
// Render the UI for all our tests
|
||||
for (var i=0; i < JSLitmus._tests.length; i++)
|
||||
JSLitmus.renderTest(JSLitmus._tests[i]);
|
||||
},
|
||||
|
||||
/**
|
||||
* (Re)render all the test results
|
||||
*/
|
||||
renderAll: function() {
|
||||
for (var i = 0; i < JSLitmus._tests.length; i++)
|
||||
JSLitmus.renderTest(JSLitmus._tests[i]);
|
||||
JSLitmus.renderChart();
|
||||
},
|
||||
|
||||
/**
|
||||
* (Re)render the chart graphics
|
||||
*/
|
||||
renderChart: function() {
|
||||
var url = JSLitmus.chartUrl();
|
||||
jsl.$('chart_link').href = url;
|
||||
jsl.$('chart_image').src = url;
|
||||
jsl.$('chart').style.display = '';
|
||||
|
||||
// Update the tiny URL
|
||||
jsl.$('tiny_url').src = 'http://tinyurl.com/api-create.php?url='+escape(url);
|
||||
},
|
||||
|
||||
/**
|
||||
* (Re)render the results for a specific test
|
||||
*/
|
||||
renderTest: function(test) {
|
||||
// Make a new row if needed
|
||||
if (!test._row) {
|
||||
var trow = jsl.$('test_row_template');
|
||||
if (!trow) return;
|
||||
|
||||
test._row = trow.cloneNode(true);
|
||||
test._row.style.display = '';
|
||||
test._row.id = '';
|
||||
test._row.onclick = function() {JSLitmus._queueTest(test);};
|
||||
test._row.title = 'Run ' + test.name + ' test';
|
||||
trow.parentNode.appendChild(test._row);
|
||||
test._row.cells[0].innerHTML = test.name;
|
||||
}
|
||||
|
||||
var cell = test._row.cells[1];
|
||||
var cns = [test.loopArg ? 'test_looping' : 'test_nonlooping'];
|
||||
|
||||
if (test.error) {
|
||||
cns.push('test_error');
|
||||
cell.innerHTML =
|
||||
'<div class="error_head">' + test.error + '</div>' +
|
||||
'<ul class="error_body"><li>' +
|
||||
jsl.join(test.error, ': ', '</li><li>') +
|
||||
'</li></ul>';
|
||||
} else {
|
||||
if (test.running) {
|
||||
cns.push('test_running');
|
||||
cell.innerHTML = 'running';
|
||||
} else if (jsl.indexOf(JSLitmus._queue, test) >= 0) {
|
||||
cns.push('test_pending');
|
||||
cell.innerHTML = 'pending';
|
||||
} else if (test.count) {
|
||||
cns.push('test_done');
|
||||
var hz = test.getHz(jsl.$('test_normalize').checked);
|
||||
cell.innerHTML = hz != Infinity ? hz : '∞';
|
||||
cell.title = 'Looped ' + test.count + ' times in ' + test.time + ' seconds';
|
||||
} else {
|
||||
cell.innerHTML = 'ready';
|
||||
}
|
||||
}
|
||||
cell.className = cns.join(' ');
|
||||
},
|
||||
|
||||
/**
|
||||
* Create a new test
|
||||
*/
|
||||
test: function(name, f) {
|
||||
// Create the Test object
|
||||
var test = new Test(name, f);
|
||||
JSLitmus._tests.push(test);
|
||||
|
||||
// Re-render if the test state changes
|
||||
test.onChange = JSLitmus.renderTest;
|
||||
|
||||
// Run the next test if this one finished
|
||||
test.onStop = function(test) {
|
||||
if (JSLitmus.onTestFinish) JSLitmus.onTestFinish(test);
|
||||
JSLitmus.currentTest = null;
|
||||
JSLitmus._nextTest();
|
||||
};
|
||||
|
||||
// Render the new test
|
||||
this.renderTest(test);
|
||||
},
|
||||
|
||||
/**
|
||||
* Add all tests to the run queue
|
||||
*/
|
||||
runAll: function(e) {
|
||||
e = e || window.event;
|
||||
var reverse = e && e.shiftKey, len = JSLitmus._tests.length;
|
||||
for (var i = 0; i < len; i++) {
|
||||
JSLitmus._queueTest(JSLitmus._tests[!reverse ? i : (len - i - 1)]);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Remove all tests from the run queue. The current test has to finish on
|
||||
* it's own though
|
||||
*/
|
||||
stop: function() {
|
||||
while (JSLitmus._queue.length) {
|
||||
var test = JSLitmus._queue.shift();
|
||||
JSLitmus.renderTest(test);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Run the next test in the run queue
|
||||
*/
|
||||
_nextTest: function() {
|
||||
if (!JSLitmus.currentTest) {
|
||||
var test = JSLitmus._queue.shift();
|
||||
if (test) {
|
||||
jsl.$('stop_button').disabled = false;
|
||||
JSLitmus.currentTest = test;
|
||||
test.run();
|
||||
JSLitmus.renderTest(test);
|
||||
if (JSLitmus.onTestStart) JSLitmus.onTestStart(test);
|
||||
} else {
|
||||
jsl.$('stop_button').disabled = true;
|
||||
JSLitmus.renderChart();
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Add a test to the run queue
|
||||
*/
|
||||
_queueTest: function(test) {
|
||||
if (jsl.indexOf(JSLitmus._queue, test) >= 0) return;
|
||||
JSLitmus._queue.push(test);
|
||||
JSLitmus.renderTest(test);
|
||||
JSLitmus._nextTest();
|
||||
},
|
||||
|
||||
/**
|
||||
* Generate a Google Chart URL that shows the data for all tests
|
||||
*/
|
||||
chartUrl: function() {
|
||||
var n = JSLitmus._tests.length, markers = [], data = [];
|
||||
var d, min = 0, max = -1e10;
|
||||
var normalize = jsl.$('test_normalize').checked;
|
||||
|
||||
// Gather test data
|
||||
for (var i=0; i < JSLitmus._tests.length; i++) {
|
||||
var test = JSLitmus._tests[i];
|
||||
if (test.count) {
|
||||
var hz = test.getHz(normalize);
|
||||
var v = hz != Infinity ? hz : 0;
|
||||
data.push(v);
|
||||
markers.push('t' + jsl.escape(test.name + '(' + jsl.toLabel(hz)+ ')') + ',000000,0,' +
|
||||
markers.length + ',10');
|
||||
max = Math.max(v, max);
|
||||
}
|
||||
}
|
||||
if (markers.length <= 0) return null;
|
||||
|
||||
// Build chart title
|
||||
var title = document.getElementsByTagName('title');
|
||||
title = (title && title.length) ? title[0].innerHTML : null;
|
||||
var chart_title = [];
|
||||
if (title) chart_title.push(title);
|
||||
chart_title.push('Ops/sec (' + platform + ')');
|
||||
|
||||
// Build labels
|
||||
var labels = [jsl.toLabel(min), jsl.toLabel(max)];
|
||||
|
||||
var w = 250, bw = 15;
|
||||
var bs = 5;
|
||||
var h = markers.length*(bw + bs) + 30 + chart_title.length*20;
|
||||
|
||||
var params = {
|
||||
chtt: escape(chart_title.join('|')),
|
||||
chts: '000000,10',
|
||||
cht: 'bhg', // chart type
|
||||
chd: 't:' + data.join(','), // data set
|
||||
chds: min + ',' + max, // max/min of data
|
||||
chxt: 'x', // label axes
|
||||
chxl: '0:|' + labels.join('|'), // labels
|
||||
chsp: '0,1',
|
||||
chm: markers.join('|'), // test names
|
||||
chbh: [bw, 0, bs].join(','), // bar widths
|
||||
// chf: 'bg,lg,0,eeeeee,0,eeeeee,.5,ffffff,1', // gradient
|
||||
chs: w + 'x' + h
|
||||
};
|
||||
return 'http://chart.apis.google.com/chart?' + jsl.join(params, '=', '&');
|
||||
}
|
||||
};
|
||||
|
||||
JSLitmus._init();
|
||||
})();
|
||||
481
vendor/backbone/test/vendor/json2.js
vendored
481
vendor/backbone/test/vendor/json2.js
vendored
@@ -1,481 +0,0 @@
|
||||
/*
|
||||
http://www.JSON.org/json2.js
|
||||
2009-09-29
|
||||
|
||||
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 ' '),
|
||||
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 evil: true, strict: false */
|
||||
|
||||
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", 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 (!this.JSON) {
|
||||
this.JSON = {};
|
||||
}
|
||||
|
||||
(function () {
|
||||
|
||||
function f(n) {
|
||||
// Format integers to have at least two digits.
|
||||
return n < 10 ? '0' + n : n;
|
||||
}
|
||||
|
||||
if (typeof Date.prototype.toJSON !== 'function') {
|
||||
|
||||
Date.prototype.toJSON = function (key) {
|
||||
|
||||
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;
|
||||
};
|
||||
|
||||
String.prototype.toJSON =
|
||||
Number.prototype.toJSON =
|
||||
Boolean.prototype.toJSON = function (key) {
|
||||
return this.valueOf();
|
||||
};
|
||||
}
|
||||
|
||||
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
|
||||
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
|
||||
gap,
|
||||
indent,
|
||||
meta = { // table of character substitutions
|
||||
'\b': '\\b',
|
||||
'\t': '\\t',
|
||||
'\n': '\\n',
|
||||
'\f': '\\f',
|
||||
'\r': '\\r',
|
||||
'"' : '\\"',
|
||||
'\\': '\\\\'
|
||||
},
|
||||
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) {
|
||||
k = rep[i];
|
||||
if (typeof k === 'string') {
|
||||
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.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') {
|
||||
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') {
|
||||
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.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.
|
||||
|
||||
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');
|
||||
};
|
||||
}
|
||||
}());
|
||||
236
vendor/backbone/test/vendor/qunit.css
vendored
236
vendor/backbone/test/vendor/qunit.css
vendored
@@ -1,236 +0,0 @@
|
||||
/**
|
||||
* QUnit v1.8.0 - A JavaScript Unit Testing Framework
|
||||
*
|
||||
* http://docs.jquery.com/QUnit
|
||||
*
|
||||
* Copyright (c) 2012 John Resig, Jörn Zaefferer
|
||||
* Dual licensed under the MIT (MIT-LICENSE.txt)
|
||||
* or GPL (GPL-LICENSE.txt) licenses.
|
||||
*/
|
||||
|
||||
/** 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-tests ol, #qunit-header, #qunit-banner, #qunit-userAgent, #qunit-testresult {
|
||||
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: 15px 15px 0 0;
|
||||
-moz-border-radius: 15px 15px 0 0;
|
||||
-webkit-border-top-right-radius: 15px;
|
||||
-webkit-border-top-left-radius: 15px;
|
||||
}
|
||||
|
||||
#qunit-header a {
|
||||
text-decoration: none;
|
||||
color: #c2ccd1;
|
||||
}
|
||||
|
||||
#qunit-header a:hover,
|
||||
#qunit-header a:focus {
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
#qunit-header label {
|
||||
display: inline-block;
|
||||
padding-left: 0.5em;
|
||||
}
|
||||
|
||||
#qunit-banner {
|
||||
height: 5px;
|
||||
}
|
||||
|
||||
#qunit-testrunner-toolbar {
|
||||
padding: 0.5em 0 0.5em 2em;
|
||||
color: #5E740B;
|
||||
background-color: #eee;
|
||||
}
|
||||
|
||||
#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;
|
||||
}
|
||||
|
||||
|
||||
/** 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 ol {
|
||||
margin-top: 0.5em;
|
||||
padding: 0.5em;
|
||||
|
||||
background-color: #fff;
|
||||
|
||||
border-radius: 15px;
|
||||
-moz-border-radius: 15px;
|
||||
-webkit-border-radius: 15px;
|
||||
|
||||
box-shadow: inset 0px 2px 13px #999;
|
||||
-moz-box-shadow: inset 0px 2px 13px #999;
|
||||
-webkit-box-shadow: inset 0px 2px 13px #999;
|
||||
}
|
||||
|
||||
#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 {
|
||||
margin: 0.5em;
|
||||
padding: 0.4em 0.5em 0.4em 0.5em;
|
||||
background-color: #fff;
|
||||
border-bottom: none;
|
||||
list-style-position: inside;
|
||||
}
|
||||
|
||||
/*** Passing Styles */
|
||||
|
||||
#qunit-tests li li.pass {
|
||||
color: #5E740B;
|
||||
background-color: #fff;
|
||||
border-left: 26px 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: 26px solid #EE5757;
|
||||
white-space: pre;
|
||||
}
|
||||
|
||||
#qunit-tests > li:last-child {
|
||||
border-radius: 0 0 15px 15px;
|
||||
-moz-border-radius: 0 0 15px 15px;
|
||||
-webkit-border-bottom-right-radius: 15px;
|
||||
-webkit-border-bottom-left-radius: 15px;
|
||||
}
|
||||
|
||||
#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;
|
||||
}
|
||||
1863
vendor/backbone/test/vendor/qunit.js
vendored
1863
vendor/backbone/test/vendor/qunit.js
vendored
File diff suppressed because it is too large
Load Diff
262
vendor/backbone/test/view.js
vendored
262
vendor/backbone/test/view.js
vendored
@@ -7,33 +7,37 @@ $(document).ready(function() {
|
||||
setup: function() {
|
||||
view = new Backbone.View({
|
||||
id : 'test-view',
|
||||
className : 'test-view'
|
||||
className : 'test-view',
|
||||
other : 'non-special-option'
|
||||
});
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
test("View: constructor", 4, 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("View: jQuery", 2, function() {
|
||||
view.setElement(document.body);
|
||||
ok(view.$('#qunit-header a').get(0).innerHTML.match(/Backbone Test Suite/));
|
||||
ok(view.$('#qunit-header a').get(1).innerHTML.match(/Backbone Speed Suite/));
|
||||
test("jQuery", 1, function() {
|
||||
var view = new Backbone.View;
|
||||
view.setElement('<p><a><b>test</b></a></p>');
|
||||
strictEqual(view.$('a b').html(), 'test');
|
||||
});
|
||||
|
||||
test("View: make", 3, function() {
|
||||
test("make", 3, function() {
|
||||
var div = view.make('div', {id: 'test-div'}, "one two three");
|
||||
|
||||
equal(div.tagName.toLowerCase(), 'div');
|
||||
equal(div.id, 'test-div');
|
||||
equal($(div).text(), 'one two three');
|
||||
});
|
||||
|
||||
test("View: make can take falsy values for content", 2, function() {
|
||||
test("make can take falsy values for content", 2, function() {
|
||||
var div = view.make('div', {id: 'test-div'}, 0);
|
||||
equal($(div).text(), '0');
|
||||
|
||||
@@ -41,101 +45,113 @@ $(document).ready(function() {
|
||||
equal($(div).text(), '');
|
||||
});
|
||||
|
||||
test("View: initialize", 1, function() {
|
||||
test("initialize", 1, function() {
|
||||
var View = Backbone.View.extend({
|
||||
initialize: function() {
|
||||
this.one = 1;
|
||||
}
|
||||
});
|
||||
var view = new View;
|
||||
equal(view.one, 1);
|
||||
|
||||
strictEqual(new View().one, 1);
|
||||
});
|
||||
|
||||
test("View: delegateEvents", 6, function() {
|
||||
var counter = 0;
|
||||
var counter2 = 0;
|
||||
view.setElement(document.body);
|
||||
view.increment = function(){ counter++; };
|
||||
view.$el.bind('click', function(){ counter2++; });
|
||||
var events = {"click #qunit-banner": "increment"};
|
||||
test("delegateEvents", 6, function() {
|
||||
var counter1 = 0, counter2 = 0;
|
||||
|
||||
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 #test': 'increment'};
|
||||
|
||||
view.delegateEvents(events);
|
||||
$('#qunit-banner').trigger('click');
|
||||
equal(counter, 1);
|
||||
view.$('#test').trigger('click');
|
||||
equal(counter1, 1);
|
||||
equal(counter2, 1);
|
||||
$('#qunit-banner').trigger('click');
|
||||
equal(counter, 2);
|
||||
|
||||
view.$('#test').trigger('click');
|
||||
equal(counter1, 2);
|
||||
equal(counter2, 2);
|
||||
|
||||
view.delegateEvents(events);
|
||||
$('#qunit-banner').trigger('click');
|
||||
equal(counter, 3);
|
||||
view.$('#test').trigger('click');
|
||||
equal(counter1, 3);
|
||||
equal(counter2, 3);
|
||||
});
|
||||
|
||||
test("View: delegateEvents allows functions for callbacks", 3, function() {
|
||||
test("delegateEvents allows functions for callbacks", 3, function() {
|
||||
var view = new Backbone.View({el: '<p></p>'});
|
||||
view.counter = 0;
|
||||
view.setElement("#qunit-banner");
|
||||
var events = {"click": function() { this.counter++; }};
|
||||
|
||||
var events = {
|
||||
click: function() {
|
||||
this.counter++;
|
||||
}
|
||||
};
|
||||
|
||||
view.delegateEvents(events);
|
||||
$('#qunit-banner').trigger('click');
|
||||
view.$el.trigger('click');
|
||||
equal(view.counter, 1);
|
||||
$('#qunit-banner').trigger('click');
|
||||
|
||||
view.$el.trigger('click');
|
||||
equal(view.counter, 2);
|
||||
|
||||
view.delegateEvents(events);
|
||||
$('#qunit-banner').trigger('click');
|
||||
view.$el.trigger('click');
|
||||
equal(view.counter, 3);
|
||||
});
|
||||
|
||||
test("View: undelegateEvents", 6, function() {
|
||||
var counter = 0;
|
||||
var counter2 = 0;
|
||||
view.setElement(document.body);
|
||||
view.increment = function(){ counter++; };
|
||||
$(view.el).unbind('click');
|
||||
$(view.el).bind('click', function(){ counter2++; });
|
||||
var events = {"click #qunit-userAgent": "increment"};
|
||||
test("undelegateEvents", 6, function() {
|
||||
var counter1 = 0, counter2 = 0;
|
||||
|
||||
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 #test': 'increment'};
|
||||
|
||||
view.delegateEvents(events);
|
||||
$('#qunit-userAgent').trigger('click');
|
||||
equal(counter, 1);
|
||||
view.$('#test').trigger('click');
|
||||
equal(counter1, 1);
|
||||
equal(counter2, 1);
|
||||
|
||||
view.undelegateEvents();
|
||||
$('#qunit-userAgent').trigger('click');
|
||||
equal(counter, 1);
|
||||
view.$('#test').trigger('click');
|
||||
equal(counter1, 1);
|
||||
equal(counter2, 2);
|
||||
|
||||
view.delegateEvents(events);
|
||||
$('#qunit-userAgent').trigger('click');
|
||||
equal(counter, 2);
|
||||
view.$('#test').trigger('click');
|
||||
equal(counter1, 2);
|
||||
equal(counter2, 3);
|
||||
});
|
||||
|
||||
test("View: _ensureElement with DOM node el", 1, function() {
|
||||
var ViewClass = Backbone.View.extend({
|
||||
test("_ensureElement with DOM node el", 1, function() {
|
||||
var View = Backbone.View.extend({
|
||||
el: document.body
|
||||
});
|
||||
var view = new ViewClass;
|
||||
equal(view.el, document.body);
|
||||
|
||||
equal(new View().el, document.body);
|
||||
});
|
||||
|
||||
test("View: _ensureElement with string el", 3, function() {
|
||||
var ViewClass = Backbone.View.extend({
|
||||
test("_ensureElement with string el", 3, function() {
|
||||
var View = Backbone.View.extend({
|
||||
el: "body"
|
||||
});
|
||||
var view = new ViewClass;
|
||||
strictEqual(view.el, document.body);
|
||||
strictEqual(new View().el, document.body);
|
||||
|
||||
ViewClass = Backbone.View.extend({
|
||||
View = Backbone.View.extend({
|
||||
el: "#testElement > h1"
|
||||
});
|
||||
view = new ViewClass;
|
||||
strictEqual(view.el, $("#testElement > h1").get(0));
|
||||
strictEqual(new View().el, $("#testElement > h1").get(0));
|
||||
|
||||
ViewClass = Backbone.View.extend({
|
||||
View = Backbone.View.extend({
|
||||
el: "#nonexistent"
|
||||
});
|
||||
view = new ViewClass;
|
||||
ok(!view.el);
|
||||
ok(!new View().el);
|
||||
});
|
||||
|
||||
test("View: with className and id functions", 2, function() {
|
||||
test("with className and id functions", 2, function() {
|
||||
var View = Backbone.View.extend({
|
||||
className: function() {
|
||||
return 'className';
|
||||
@@ -144,53 +160,63 @@ $(document).ready(function() {
|
||||
return 'id';
|
||||
}
|
||||
});
|
||||
var view = new View();
|
||||
strictEqual(view.el.className, 'className');
|
||||
strictEqual(view.el.id, 'id');
|
||||
|
||||
strictEqual(new View().el.className, 'className');
|
||||
strictEqual(new View().el.id, 'id');
|
||||
});
|
||||
|
||||
test("View: with attributes", 2, function() {
|
||||
var view = new Backbone.View({attributes : {'class': 'one', id: 'two'}});
|
||||
equal(view.el.className, 'one');
|
||||
equal(view.el.id, 'two');
|
||||
test("with attributes", 2, function() {
|
||||
var View = Backbone.View.extend({
|
||||
attributes: {
|
||||
id: 'id',
|
||||
'class': 'class'
|
||||
}
|
||||
});
|
||||
|
||||
strictEqual(new View().el.className, 'class');
|
||||
strictEqual(new View().el.id, 'id');
|
||||
});
|
||||
|
||||
test("View: with attributes as a function", 1, function() {
|
||||
var viewClass = Backbone.View.extend({
|
||||
test("with attributes as a function", 1, function() {
|
||||
var View = Backbone.View.extend({
|
||||
attributes: function() {
|
||||
return {'class': 'dynamic'};
|
||||
}
|
||||
});
|
||||
equal((new viewClass).el.className, 'dynamic');
|
||||
|
||||
strictEqual(new View().el.className, 'dynamic');
|
||||
});
|
||||
|
||||
test("View: multiple views per element", 3, function() {
|
||||
var count = 0, ViewClass = Backbone.View.extend({
|
||||
el: $("body"),
|
||||
test("multiple views per element", 3, function() {
|
||||
var count = 0;
|
||||
var $el = $('<p></p>');
|
||||
|
||||
var View = Backbone.View.extend({
|
||||
el: $el,
|
||||
events: {
|
||||
"click": "click"
|
||||
},
|
||||
click: function() {
|
||||
count++;
|
||||
click: function() {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
var view1 = new ViewClass;
|
||||
$("body").trigger("click");
|
||||
var view1 = new View;
|
||||
$el.trigger("click");
|
||||
equal(1, count);
|
||||
|
||||
var view2 = new ViewClass;
|
||||
$("body").trigger("click");
|
||||
var view2 = new View;
|
||||
$el.trigger("click");
|
||||
equal(3, count);
|
||||
|
||||
view1.delegateEvents();
|
||||
$("body").trigger("click");
|
||||
$el.trigger("click");
|
||||
equal(5, count);
|
||||
});
|
||||
|
||||
test("View: custom events, with namespaces", 2, function() {
|
||||
test("custom events, with namespaces", 2, function() {
|
||||
var count = 0;
|
||||
var ViewClass = Backbone.View.extend({
|
||||
|
||||
var View = Backbone.View.extend({
|
||||
el: $('body'),
|
||||
events: function() {
|
||||
return {"fake$event.namespaced": "run"};
|
||||
@@ -200,9 +226,10 @@ $(document).ready(function() {
|
||||
}
|
||||
});
|
||||
|
||||
var view = new ViewClass;
|
||||
var view = new View;
|
||||
$('body').trigger('fake$event').trigger('fake$event');
|
||||
equal(count, 2);
|
||||
|
||||
$('body').unbind('.namespaced');
|
||||
$('body').trigger('fake$event');
|
||||
equal(count, 2);
|
||||
@@ -210,59 +237,98 @@ $(document).ready(function() {
|
||||
|
||||
test("#1048 - setElement uses provided object.", 2, function() {
|
||||
var $el = $('body');
|
||||
|
||||
var view = new Backbone.View({el: $el});
|
||||
ok(view.$el === $el);
|
||||
|
||||
view.setElement($el = $($el));
|
||||
ok(view.$el === $el);
|
||||
});
|
||||
|
||||
test("#986 - Undelegate before changing element.", 1, function() {
|
||||
var a = $('<button></button>');
|
||||
var b = $('<button></button>');
|
||||
var button1 = $('<button></button>');
|
||||
var button2 = $('<button></button>');
|
||||
|
||||
var View = Backbone.View.extend({
|
||||
events: {click: function(e) { ok(view.el === e.target); }}
|
||||
events: {
|
||||
click: function(e) {
|
||||
ok(view.el === e.target);
|
||||
}
|
||||
}
|
||||
});
|
||||
var view = new View({el: a});
|
||||
view.setElement(b);
|
||||
a.trigger('click');
|
||||
b.trigger('click');
|
||||
|
||||
var view = new View({el: button1});
|
||||
view.setElement(button2);
|
||||
|
||||
button1.trigger('click');
|
||||
button2.trigger('click');
|
||||
});
|
||||
|
||||
test("#1172 - Clone attributes object", 2, function() {
|
||||
var View = Backbone.View.extend({attributes: {foo: 'bar'}});
|
||||
var v1 = new View({id: 'foo'});
|
||||
strictEqual(v1.el.id, 'foo');
|
||||
var v2 = new View();
|
||||
ok(!v2.el.id);
|
||||
var View = Backbone.View.extend({
|
||||
attributes: {foo: 'bar'}
|
||||
});
|
||||
|
||||
var view1 = new View({id: 'foo'});
|
||||
strictEqual(view1.el.id, 'foo');
|
||||
|
||||
var view2 = new View();
|
||||
ok(!view2.el.id);
|
||||
});
|
||||
|
||||
test("#1228 - tagName can be provided as a function", 1, function() {
|
||||
var View = Backbone.View.extend({tagName: function(){ return 'p'; }});
|
||||
var View = Backbone.View.extend({
|
||||
tagName: function() {
|
||||
return 'p';
|
||||
}
|
||||
});
|
||||
|
||||
ok(new View().$el.is('p'));
|
||||
});
|
||||
|
||||
test("dispose", 0, function() {
|
||||
var View = Backbone.View.extend({
|
||||
events: {click: function(){ ok(false); }},
|
||||
events: {
|
||||
click: function() { ok(false); }
|
||||
},
|
||||
initialize: function() {
|
||||
this.model.on('all x', function(){ ok(false); }, this);
|
||||
this.collection.on('all x', function(){ ok(false); }, this);
|
||||
}
|
||||
});
|
||||
|
||||
var view = new View({
|
||||
model: new Backbone.Model,
|
||||
collection: new Backbone.Collection
|
||||
});
|
||||
|
||||
view.dispose();
|
||||
view.model.trigger('x');
|
||||
view.collection.trigger('x');
|
||||
view.$el.click();
|
||||
});
|
||||
|
||||
test("dispose with non Backbone objects", 0, function() {
|
||||
var view = new Backbone.View({model: {}, collection: {}});
|
||||
view.dispose();
|
||||
});
|
||||
|
||||
test("view#remove calls dispose.", 1, function() {
|
||||
var view = new Backbone.View();
|
||||
|
||||
view.dispose = function() { ok(true); };
|
||||
view.remove();
|
||||
});
|
||||
|
||||
test("Provide function for el.", 1, function() {
|
||||
var View = Backbone.View.extend({
|
||||
el: function() {
|
||||
return "<p><a></a></p>";
|
||||
}
|
||||
});
|
||||
|
||||
var view = new View;
|
||||
ok(view.$el.is('p:has(a)'));
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
1
vendor/benchmark.js/README.md
vendored
1
vendor/benchmark.js/README.md
vendored
@@ -1,4 +1,5 @@
|
||||
# Benchmark.js <sup>v1.0.0</sup>
|
||||
[](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/).
|
||||
|
||||
|
||||
41
vendor/benchmark.js/benchmark.js
vendored
41
vendor/benchmark.js/benchmark.js
vendored
@@ -320,6 +320,7 @@
|
||||
/** Math shortcuts */
|
||||
var abs = Math.abs,
|
||||
floor = Math.floor,
|
||||
log = Math.log,
|
||||
max = Math.max,
|
||||
min = Math.min,
|
||||
pow = Math.pow,
|
||||
@@ -945,6 +946,20 @@
|
||||
(/^[\s(]*function[^(]*\(([^\s,)]+)/.exec(fn) || 0)[1]) || '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the geometric mean (log-average) of a sample.
|
||||
* See http://en.wikipedia.org/wiki/Geometric_mean#Relationship_with_arithmetic_mean_of_logarithms.
|
||||
*
|
||||
* @private
|
||||
* @param {Array} sample The sample.
|
||||
* @returns {Number} The geometric mean.
|
||||
*/
|
||||
function getGeometricMean(sample) {
|
||||
return pow(Math.E, reduce(sample, function(sum, x) {
|
||||
return sum + log(x);
|
||||
}) / sample.length) || 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the arithmetic mean of a sample.
|
||||
*
|
||||
@@ -953,9 +968,9 @@
|
||||
* @returns {Number} The mean.
|
||||
*/
|
||||
function getMean(sample) {
|
||||
return reduce(sample, function(sum, x) {
|
||||
return (reduce(sample, function(sum, x) {
|
||||
return sum + x;
|
||||
}) / sample.length || 0;
|
||||
}) / sample.length) || 0;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2076,6 +2091,10 @@
|
||||
event.aborted = me.aborted;
|
||||
},
|
||||
'onComplete': function(event) {
|
||||
me.score = getGeometricMean(map(me, function(bench) {
|
||||
return bench.reference / (bench.times.period * 1e6);
|
||||
})) || 0;
|
||||
|
||||
me.running = false;
|
||||
me.emit(event);
|
||||
}
|
||||
@@ -3169,7 +3188,15 @@
|
||||
* @memberOf Benchmark.options
|
||||
* @type Function
|
||||
*/
|
||||
'onStart': undefined
|
||||
'onStart': undefined,
|
||||
|
||||
/**
|
||||
* The reference time taken to execute the test once (usecs).
|
||||
*
|
||||
* @memberOf Benchmark.options
|
||||
* @type Number
|
||||
*/
|
||||
'reference': 0
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -3726,6 +3753,14 @@
|
||||
*/
|
||||
'length': 0,
|
||||
|
||||
/**
|
||||
* A score computed using the normalized result of each benchmark in the suite.
|
||||
*
|
||||
* @memberOf Benchmark.Suite
|
||||
* @type Number
|
||||
*/
|
||||
'score': 0,
|
||||
|
||||
/**
|
||||
* A flag to indicate if the suite is aborted.
|
||||
*
|
||||
|
||||
2
vendor/docdown/docdown.php
vendored
2
vendor/docdown/docdown.php
vendored
@@ -8,7 +8,7 @@ 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
|
||||
|
||||
215
vendor/docdown/src/DocDown/Alias.php
vendored
Normal file
215
vendor/docdown/src/DocDown/Alias.php
vendored
Normal file
@@ -0,0 +1,215 @@
|
||||
<?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->_lineNumber = $owner->getLineNumber();
|
||||
$this->_members = $owner->getMembers();
|
||||
$this->_params = $owner->getParams();
|
||||
$this->_returns = $owner->getReturns();
|
||||
$this->_type = $owner->getType();
|
||||
$this->_isCtor = $owner->isCtor();
|
||||
$this->_isPlugin = $owner->isPlugin();
|
||||
$this->_isPrivate = $owner->isPrivate();
|
||||
$this->_isStatic = $owner->isStatic();
|
||||
}
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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* 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;
|
||||
}
|
||||
}
|
||||
?>
|
||||
238
vendor/docdown/src/DocDown/Entry.php
vendored
238
vendor/docdown/src/DocDown/Entry.php
vendored
@@ -1,5 +1,7 @@
|
||||
<?php
|
||||
|
||||
require(dirname(__FILE__) . "/Alias.php");
|
||||
|
||||
/**
|
||||
* A class to simplify parsing a single JSDoc entry.
|
||||
*/
|
||||
@@ -37,7 +39,7 @@ class Entry {
|
||||
* @constructor
|
||||
* @param {String} $entry The documentation entry to analyse.
|
||||
* @param {String} $source The source code.
|
||||
* @param {String} $lang The language highlighter used for code examples.
|
||||
* @param {String} [$lang ='js'] The language highlighter used for code examples.
|
||||
*/
|
||||
public function __construct( $entry, $source, $lang = 'js' ) {
|
||||
$this->entry = $entry;
|
||||
@@ -70,16 +72,46 @@ class Entry {
|
||||
* @returns {Boolean} Returns `true` if the entry is a function reference, else `false`.
|
||||
*/
|
||||
private function isFunction() {
|
||||
return !!(
|
||||
$this->isCtor() ||
|
||||
count($this->getParams()) ||
|
||||
count($this->getReturns()) ||
|
||||
preg_match('/\*\s*@function\b/', $this->entry)
|
||||
);
|
||||
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.
|
||||
*
|
||||
@@ -87,13 +119,17 @@ class 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('#\*\s*@name\s+([^\n]+)#', $this->entry, $name);
|
||||
preg_match('#\* *@name\s+([^\n]+)#', $this->entry, $name);
|
||||
if (count($name)) {
|
||||
$name = trim($name[1]);
|
||||
} else {
|
||||
@@ -111,178 +147,263 @@ class Entry {
|
||||
$result = $name .'('. implode(array_slice($result, 1), ', ') .')';
|
||||
$result = str_replace(', [', ' [, ', str_replace('], [', ', ', $result));
|
||||
}
|
||||
return $result ? $result : $name;
|
||||
|
||||
$this->_call = $result ? $result : $name;
|
||||
return $this->_call;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the entry description.
|
||||
* Extracts the entry's `category` data.
|
||||
*
|
||||
* @memberOf Entry
|
||||
* @returns {String} The entry description.
|
||||
* @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 = trim(preg_replace('/(?:^|\n)\s*\* ?/', ' ', $result[1]));
|
||||
$result = ($type == 'Function' ? '' : '(' . str_replace('|', ', ', trim($type, '{}')) . '): ') . $result;
|
||||
}
|
||||
$this->_desc = $result;
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the entry `example` data.
|
||||
* Extracts the entry's `example` data.
|
||||
*
|
||||
* @memberOf Entry
|
||||
* @returns {String} The entry `example` data.
|
||||
* @returns {String} The entry's `example` data.
|
||||
*/
|
||||
public function getExample() {
|
||||
preg_match('#\*\s*@example\s+([\s\S]*?)(?=\*\s\@[a-z]|\*/)#', $this->entry, $result);
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the line number of the entry.
|
||||
* Resolves the entry's line number.
|
||||
*
|
||||
* @memberOf Entry
|
||||
* @returns {Number} The line number.
|
||||
* @returns {Number} The entry's line number.
|
||||
*/
|
||||
public function getLineNumber() {
|
||||
preg_match_all('/\n/', substr($this->source, 0, strrpos($this->source, $this->entry) + strlen($this->entry)), $lines);
|
||||
return count(array_pop($lines)) + 1;
|
||||
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 `member` data.
|
||||
* Extracts the entry's `member` data.
|
||||
*
|
||||
* @memberOf Entry
|
||||
* @param {Number} $index The index of the array value to return.
|
||||
* @returns {Array|String} The entry `member` data.
|
||||
* @returns {Array|String} The entry's `member` data.
|
||||
*/
|
||||
public function getMembers( $index = null ) {
|
||||
preg_match('#\*\s*@member(?:Of)?\s+([^\n]+)#', $this->entry, $result);
|
||||
if (count($result)) {
|
||||
$result = trim(preg_replace('/(?:^|\n)\s*\* ?/', ' ', $result[1]));
|
||||
$result = preg_split('/,\s*/', $result);
|
||||
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 ? @$result[$index] : $result;
|
||||
return $index !== null
|
||||
? @$this->_members[$index]
|
||||
: $this->_members;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the entry `name` data.
|
||||
* Extracts the entry's `name` data.
|
||||
*
|
||||
* @memberOf Entry
|
||||
* @returns {String} The entry `name` data.
|
||||
* @returns {String} The entry's `name` data.
|
||||
*/
|
||||
public function getName() {
|
||||
preg_match('#\*\s*@name\s+([^\n]+)#', $this->entry, $result);
|
||||
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 `param` data.
|
||||
* Extracts the entry's `param` data.
|
||||
*
|
||||
* @memberOf Entry
|
||||
* @param {Number} $index The index of the array value to return.
|
||||
* @returns {Array} The entry `param` data.
|
||||
* @returns {Array} The entry's `param` data.
|
||||
*/
|
||||
public function getParams( $index = null ) {
|
||||
preg_match_all('#\*\s*@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();
|
||||
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[0][$key][] = trim(preg_replace('/(?:^|\n)\s*\* */', ' ', $value));
|
||||
}
|
||||
$result = $result[0];
|
||||
}
|
||||
$result = $result[0];
|
||||
$this->_params = $result;
|
||||
}
|
||||
return $index !== null ? @$result[$index] : $result;
|
||||
return $index !== null
|
||||
? @$this->_params[$index]
|
||||
: $this->_params;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the entry `returns` data.
|
||||
* Extracts the entry's `returns` data.
|
||||
*
|
||||
* @memberOf Entry
|
||||
* @returns {String} The entry `returns` data.
|
||||
* @returns {String} The entry's `returns` data.
|
||||
*/
|
||||
public function getReturns() {
|
||||
preg_match('#\*\s*@returns\s+\{([^}]+)\}\s+([\s\S]*?)(?=\*\s\@[a-z]|\*/)#', $this->entry, $result);
|
||||
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 `type` data.
|
||||
* Extracts the entry's `type` data.
|
||||
*
|
||||
* @memberOf Entry
|
||||
* @returns {String} The entry `type` data.
|
||||
* @returns {String} The entry's `type` data.
|
||||
*/
|
||||
public function getType() {
|
||||
preg_match('#\*\s*@type\s+([^\n]+)#', $this->entry, $result);
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if an entry is a constructor.
|
||||
* Checks if the entry is an alias.
|
||||
*
|
||||
* @memberOf Entry
|
||||
* @returns {Boolean} Returns true if a constructor, else false.
|
||||
* @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() {
|
||||
return !!preg_match('/\*\s*@constructor\b/', $this->entry);
|
||||
if (!isset($this->_isCtor)) {
|
||||
$this->_isCtor = !!preg_match('/\* *@constructor\b/', $this->entry);
|
||||
}
|
||||
return $this->_isCtor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if an entry *is* assigned to a prototype.
|
||||
* Checks if the entry *is* assigned to a prototype.
|
||||
*
|
||||
* @memberOf Entry
|
||||
* @returns {Boolean} Returns true if assigned to a prototype, else false.
|
||||
* @returns {Boolean} Returns `true` if assigned to a prototype, else `false`.
|
||||
*/
|
||||
public function isPlugin() {
|
||||
return !$this->isCtor() && !$this->isPrivate() && !$this->isStatic();
|
||||
if (!isset($this->_isPlugin)) {
|
||||
$this->_isPlugin = !$this->isCtor() && !$this->isPrivate() && !$this->isStatic();
|
||||
}
|
||||
return $this->_isPlugin;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if an entry is private.
|
||||
* Checks if the entry is private.
|
||||
*
|
||||
* @memberOf Entry
|
||||
* @returns {Boolean} Returns true if private, else false.
|
||||
* @returns {Boolean} Returns `true` if private, else `false`.
|
||||
*/
|
||||
public function isPrivate() {
|
||||
return !!preg_match('/\*\s*@private\b/', $this->entry) || strrpos($this->entry, '@') === false;
|
||||
if (!isset($this->_isPrivate)) {
|
||||
$this->_isPrivate = !!preg_match('/\* *@private\b/', $this->entry) || !preg_match('/\* *@[a-z]+\b/', $this->entry);
|
||||
}
|
||||
return $this->_isPrivate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if an entry is *not* assigned to a prototype.
|
||||
* Checks if the entry is *not* assigned to a prototype.
|
||||
*
|
||||
* @memberOf Entry
|
||||
* @returns {Boolean} Returns true if not assigned to a prototype, else false.
|
||||
* @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('/\*\s*@static\b/', $this->entry);
|
||||
$result = $public && !!preg_match('/\* *@static\b/', $this->entry);
|
||||
|
||||
// set in cases where it isn't explicitly stated
|
||||
if ($public && !$result) {
|
||||
@@ -298,6 +419,7 @@ class Entry {
|
||||
$result = true;
|
||||
}
|
||||
}
|
||||
$this->_isStatic = $result;
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
|
||||
385
vendor/docdown/src/DocDown/Generator.php
vendored
385
vendor/docdown/src/DocDown/Generator.php
vendored
@@ -7,6 +7,15 @@ require(dirname(__FILE__) . "/Entry.php");
|
||||
*/
|
||||
class Generator {
|
||||
|
||||
/**
|
||||
* The HTML for the close tag.
|
||||
*
|
||||
* @static
|
||||
* @memberOf Generator
|
||||
* @type String
|
||||
*/
|
||||
public $closeTag = "\n<!-- /div -->\n";
|
||||
|
||||
/**
|
||||
* An array of JSDoc entries.
|
||||
*
|
||||
@@ -15,6 +24,15 @@ class Generator {
|
||||
*/
|
||||
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.
|
||||
*
|
||||
@@ -24,7 +42,7 @@ class Generator {
|
||||
public $options = array();
|
||||
|
||||
/**
|
||||
* The entire file's source code.
|
||||
* The file's source code.
|
||||
*
|
||||
* @memberOf Generator
|
||||
* @type String
|
||||
@@ -65,6 +83,9 @@ class Generator {
|
||||
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']);
|
||||
@@ -86,7 +107,7 @@ class Generator {
|
||||
* @param {String} $string The string to format.
|
||||
* @returns {String} The formatted string.
|
||||
*/
|
||||
private static function format($string) {
|
||||
private static function format( $string ) {
|
||||
$counter = 0;
|
||||
|
||||
// tokenize inline code snippets
|
||||
@@ -121,7 +142,7 @@ class Generator {
|
||||
* @param {Array|Object} $object The template object.
|
||||
* @returns {String} The modified string.
|
||||
*/
|
||||
private static function interpolate($string, $object) {
|
||||
private static function interpolate( $string, $object ) {
|
||||
preg_match_all('/#\{([^}]+)\}/', $string, $tokens);
|
||||
$tokens = array_unique(array_pop($tokens));
|
||||
|
||||
@@ -149,6 +170,63 @@ class Generator {
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
/**
|
||||
* 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> [Ⓢ](#{href} \"View in source\") [Ⓣ][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.
|
||||
*
|
||||
@@ -204,44 +282,85 @@ class Generator {
|
||||
*/
|
||||
public function generate() {
|
||||
$api = array();
|
||||
$byCategory = $this->options['toc'] == 'categories';
|
||||
$categories = array();
|
||||
$closeTag = $this->closeTag;
|
||||
$compiling = false;
|
||||
$openTag = "\n<!-- div -->\n";
|
||||
$closeTag = "\n<!-- /div -->\n";
|
||||
$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;
|
||||
}
|
||||
|
||||
if (!$entry->isPrivate()) {
|
||||
$name = $entry->getName();
|
||||
$members = $entry->getMembers();
|
||||
$members = count($members) ? $members : array('');
|
||||
$members = $entry->getMembers();
|
||||
$members = count($members) ? $members : array('');
|
||||
|
||||
foreach ($members as $member) {
|
||||
// create api category arrays
|
||||
if (!isset($api[$member]) && $member) {
|
||||
$api[$member] = new Entry('', '', $entry->lang);
|
||||
$api[$member]->static = array();
|
||||
$api[$member]->plugin = 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();
|
||||
}
|
||||
// append entry to api category
|
||||
if (!$member || $entry->isCtor() || ($entry->getType() == 'Object' &&
|
||||
!preg_match('/[=:]\s*null\s*[,;]?$/', $entry->entry))) {
|
||||
$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;
|
||||
}
|
||||
else if ($entry->isStatic()) {
|
||||
$api[$member]->static[] = $entry;
|
||||
foreach ($entry->getAliases() as $alias) {
|
||||
$api[$member]->static[] = $alias;
|
||||
}
|
||||
else if ($entry->isStatic()) {
|
||||
$api[$member]->static[] = $entry;
|
||||
} else if (!$entry->isCtor()) {
|
||||
$api[$member]->plugin[] = $entry;
|
||||
}
|
||||
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
|
||||
@@ -249,19 +368,19 @@ class Generator {
|
||||
function sortCompare($a, $b) {
|
||||
$score = array( 'a' => 0, 'b' => 0);
|
||||
foreach (array( 'a' => $a, 'b' => $b) as $key => $value) {
|
||||
// capitalized keys that represent constructor properties are last
|
||||
// capitalized properties are last
|
||||
if (preg_match('/[#.][A-Z]/', $value)) {
|
||||
$score[$key] = 0;
|
||||
}
|
||||
// lowercase keys with prototype properties are next to last
|
||||
// lowercase prototype properties are next to last
|
||||
else if (preg_match('/#[a-z]/', $value)) {
|
||||
$score[$key] = 1;
|
||||
}
|
||||
// lowercase keys with static properties next to first
|
||||
// lowercase static properties next to first
|
||||
else if (preg_match('/\.[a-z]/', $value)) {
|
||||
$score[$key] = 2;
|
||||
}
|
||||
// lowercase keys with no properties are first
|
||||
// root properties are first
|
||||
else if (preg_match('/^[^#.]+$/', $value)) {
|
||||
$score[$key] = 3;
|
||||
}
|
||||
@@ -291,48 +410,90 @@ class Generator {
|
||||
|
||||
/*------------------------------------------------------------------------*/
|
||||
|
||||
// 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;
|
||||
|
||||
foreach ($api as $key => $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);
|
||||
|
||||
$compiling = $compiling ? ($result[] = $closeTag) : true;
|
||||
|
||||
// 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`' : '`')
|
||||
);
|
||||
// compile TOC by categories
|
||||
if ($byCategory) {
|
||||
foreach ($categories as $category => $entries) {
|
||||
if ($compiling) {
|
||||
$result[] = $closeTag;
|
||||
} else {
|
||||
$compiling = true;
|
||||
}
|
||||
foreach ($entry->{$kind} as $subentry) {
|
||||
$subentry->hash = $this->getHash($subentry);
|
||||
$subentry->href = $this->getLineUrl($subentry);
|
||||
$subentry->member = $member;
|
||||
$subentry->separator = $this->getSeparator($subentry);
|
||||
$result[] = Generator::interpolate('* [`#{member}#{separator}#{name}`](##{hash})', $subentry);
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -345,63 +506,51 @@ class Generator {
|
||||
$compiling = false;
|
||||
$result[] = $openTag;
|
||||
|
||||
foreach ($api as $entry) {
|
||||
// add root entry
|
||||
$member = $entry->member . $entry->getName();
|
||||
$compiling = $compiling ? ($result[] = $closeTag) : true;
|
||||
|
||||
array_push($result, $openTag, '## `' . $member . '`');
|
||||
|
||||
foreach (array($entry, 'static', 'plugin') as $kind) {
|
||||
$subentries = is_string($kind) ? $entry->{$kind} : array($kind);
|
||||
|
||||
// title
|
||||
if ($kind != 'static' && $entry->getType() != 'Object' &&
|
||||
count($subentries) && $subentries[0] != $kind) {
|
||||
if ($kind == 'plugin') {
|
||||
$result[] = $closeTag;
|
||||
}
|
||||
array_push(
|
||||
$result,
|
||||
$openTag,
|
||||
'## `' . $member . ($kind == 'plugin' ? '.prototype`' : '`')
|
||||
);
|
||||
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 . '`');
|
||||
|
||||
// body
|
||||
foreach ($subentries as $subentry) {
|
||||
// description
|
||||
array_push(
|
||||
$result,
|
||||
$openTag,
|
||||
Generator::interpolate("### <a id=\"#{hash}\"></a>`#{member}#{separator}#{call}`\n<a href=\"##{hash}\">#</a> [Ⓢ](#{href} \"View in source\") [Ⓣ][1]\n\n#{desc}", $subentry)
|
||||
);
|
||||
foreach (array($entry, 'static', 'plugin') as $kind) {
|
||||
$subentries = is_string($kind) ? $entry->{$kind} : array($kind);
|
||||
|
||||
// @param
|
||||
if (count($params = $subentry->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]
|
||||
));
|
||||
// add sub-entry name
|
||||
if ($kind != 'static' && $entry->getType() != 'Object' &&
|
||||
count($subentries) && $subentries[0] != $kind) {
|
||||
if ($kind == 'plugin') {
|
||||
$result[] = $closeTag;
|
||||
}
|
||||
}
|
||||
// @returns
|
||||
if (count($returns = $subentry->getReturns())) {
|
||||
array_push(
|
||||
$result, '',
|
||||
'#### Returns',
|
||||
Generator::interpolate('(#{type}): #{desc}', array('desc' => $returns[1], 'type' => $returns[0]))
|
||||
$result,
|
||||
$openTag,
|
||||
'## `' . $member . ($kind == 'plugin' ? '.prototype`' : '`')
|
||||
);
|
||||
}
|
||||
// @example
|
||||
if ($example = $subentry->getExample()) {
|
||||
array_push($result, '', '#### Example', $example);
|
||||
}
|
||||
array_push($result, "\n* * *", $closeTag);
|
||||
$this->addEntries($result, $subentries);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
21
vendor/jquery/MIT-LICENSE.txt
vendored
Normal file
21
vendor/jquery/MIT-LICENSE.txt
vendored
Normal 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
417
vendor/jquery/README.md
vendored
Normal 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.
|
||||
File diff suppressed because it is too large
Load Diff
20
vendor/json3/LICENSE
vendored
Normal file
20
vendor/json3/LICENSE
vendored
Normal 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
124
vendor/json3/README.md
vendored
Normal file
@@ -0,0 +1,124 @@
|
||||
# JSON 3 #
|
||||
|
||||

|
||||
|
||||
**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://bestiejs.github.com/json3/lib/json3.js) *(36.5 KB; uncompressed with comments)*
|
||||
- [Production Version](http://bestiejs.github.com/json3/lib/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="http://bestiejs.github.com/json3/lib/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
783
vendor/json3/lib/json3.js
vendored
Normal 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);
|
||||
17
vendor/json3/lib/json3.min.js
vendored
Normal file
17
vendor/json3/lib/json3.min.js
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
/*! JSON v3.2.4 | http://bestiejs.github.com/json3 | Copyright 2012, Kit Cambridge | http://kit.mit-license.org */
|
||||
;(function(){var e=void 0,i=!0,k=null,l={}.toString,m,n,p="function"===typeof define&&define.c,q=!p&&"object"==typeof exports&&exports;q||p?"object"==typeof JSON&&JSON?p?q=JSON:(q.stringify=JSON.stringify,q.parse=JSON.parse):p&&(q=this.JSON={}):q=this.JSON||(this.JSON={});var r,t,u,x,z,B,C,D,E,F,G,H,I,J=new Date(-3509827334573292),K,O,P;try{J=-109252==J.getUTCFullYear()&&0===J.getUTCMonth()&&1==J.getUTCDate()&&10==J.getUTCHours()&&37==J.getUTCMinutes()&&6==J.getUTCSeconds()&&708==J.getUTCMilliseconds()}catch(Q){}
|
||||
function R(b){var c,a,d,j=b=="json";if(j||b=="json-stringify"||b=="json-parse"){if(b=="json-stringify"||j){if(c=typeof q.stringify=="function"&&J){(d=function(){return 1}).toJSON=d;try{c=q.stringify(0)==="0"&&q.stringify(new Number)==="0"&&q.stringify(new String)=='""'&&q.stringify(l)===e&&q.stringify(e)===e&&q.stringify()===e&&q.stringify(d)==="1"&&q.stringify([d])=="[1]"&&q.stringify([e])=="[null]"&&q.stringify(k)=="null"&&q.stringify([e,l,k])=="[null,null,null]"&&q.stringify({A:[d,i,false,k,"\x00\u0008\n\u000c\r\t"]})==
|
||||
'{"A":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}'&&q.stringify(k,d)==="1"&&q.stringify([1,2],k,1)=="[\n 1,\n 2\n]"&&q.stringify(new Date(-864E13))=='"-271821-04-20T00:00:00.000Z"'&&q.stringify(new Date(864E13))=='"+275760-09-13T00:00:00.000Z"'&&q.stringify(new Date(-621987552E5))=='"-000001-01-01T00:00:00.000Z"'&&q.stringify(new Date(-1))=='"1969-12-31T23:59:59.999Z"'}catch(f){c=false}}if(!j)return c}if(b=="json-parse"||j){if(typeof q.parse=="function")try{if(q.parse("0")===0&&!q.parse(false)){d=
|
||||
q.parse('{"A":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}');if(a=d.a.length==5&&d.a[0]==1){try{a=!q.parse('"\t"')}catch(o){}if(a)try{a=q.parse("01")!=1}catch(g){}}}}catch(h){a=false}if(!j)return a}return c&&a}}
|
||||
if(!R("json")){J||(K=Math.floor,O=[0,31,59,90,120,151,181,212,243,273,304,334],P=function(b,c){return O[c]+365*(b-1970)+K((b-1969+(c=+(c>1)))/4)-K((b-1901+c)/100)+K((b-1601+c)/400)});if(!(m={}.hasOwnProperty))m=function(b){var c={},a;if((c.__proto__=k,c.__proto__={toString:1},c).toString!=l)m=function(a){var b=this.__proto__,a=a in(this.__proto__=k,this);this.__proto__=b;return a};else{a=c.constructor;m=function(b){var c=(this.constructor||a).prototype;return b in this&&!(b in c&&this[b]===c[b])}}c=
|
||||
k;return m.call(this,b)};n=function(b,c){var a=0,d,j,f;(d=function(){this.valueOf=0}).prototype.valueOf=0;j=new d;for(f in j)m.call(j,f)&&a++;d=j=k;if(a)a=a==2?function(a,b){var c={},d=l.call(a)=="[object Function]",f;for(f in a)!(d&&f=="prototype")&&!m.call(c,f)&&(c[f]=1)&&m.call(a,f)&&b(f)}:function(a,b){var c=l.call(a)=="[object Function]",d,f;for(d in a)!(c&&d=="prototype")&&m.call(a,d)&&!(f=d==="constructor")&&b(d);(f||m.call(a,d="constructor"))&&b(d)};else{j=["valueOf","toString","toLocaleString",
|
||||
"propertyIsEnumerable","isPrototypeOf","hasOwnProperty","constructor"];a=function(a,b){var c=l.call(a)=="[object Function]",d;for(d in a)!(c&&d=="prototype")&&m.call(a,d)&&b(d);for(c=j.length;d=j[--c];m.call(a,d)&&b(d));}}a(b,c)};R("json-stringify")||(r={"\\":"\\\\",'"':'\\"',"\u0008":"\\b","\u000c":"\\f","\n":"\\n","\r":"\\r","\t":"\\t"},t=function(b,c){return("000000"+(c||0)).slice(-b)},u=function(b){for(var c='"',a=0,d;d=b.charAt(a);a++)c=c+('\\"\u0008\u000c\n\r\t'.indexOf(d)>-1?r[d]:r[d]=d<" "?
|
||||
"\\u00"+t(2,d.charCodeAt(0).toString(16)):d);return c+'"'},x=function(b,c,a,d,j,f,o){var g=c[b],h,s,v,w,L,M,N,y,A;if(typeof g=="object"&&g){h=l.call(g);if(h=="[object Date]"&&!m.call(g,"toJSON"))if(g>-1/0&&g<1/0){if(P){v=K(g/864E5);for(h=K(v/365.2425)+1970-1;P(h+1,0)<=v;h++);for(s=K((v-P(h,0))/30.42);P(h,s+1)<=v;s++);v=1+v-P(h,s);w=(g%864E5+864E5)%864E5;L=K(w/36E5)%24;M=K(w/6E4)%60;N=K(w/1E3)%60;w=w%1E3}else{h=g.getUTCFullYear();s=g.getUTCMonth();v=g.getUTCDate();L=g.getUTCHours();M=g.getUTCMinutes();
|
||||
N=g.getUTCSeconds();w=g.getUTCMilliseconds()}g=(h<=0||h>=1E4?(h<0?"-":"+")+t(6,h<0?-h:h):t(4,h))+"-"+t(2,s+1)+"-"+t(2,v)+"T"+t(2,L)+":"+t(2,M)+":"+t(2,N)+"."+t(3,w)+"Z"}else g=k;else if(typeof g.toJSON=="function"&&(h!="[object Number]"&&h!="[object String]"&&h!="[object Array]"||m.call(g,"toJSON")))g=g.toJSON(b)}a&&(g=a.call(c,b,g));if(g===k)return"null";h=l.call(g);if(h=="[object Boolean]")return""+g;if(h=="[object Number]")return g>-1/0&&g<1/0?""+g:"null";if(h=="[object String]")return u(g);if(typeof g==
|
||||
"object"){for(b=o.length;b--;)if(o[b]===g)throw TypeError();o.push(g);y=[];c=f;f=f+j;if(h=="[object Array]"){s=0;for(b=g.length;s<b;A||(A=i),s++){h=x(s,g,a,d,j,f,o);y.push(h===e?"null":h)}b=A?j?"[\n"+f+y.join(",\n"+f)+"\n"+c+"]":"["+y.join(",")+"]":"[]"}else{n(d||g,function(b){var c=x(b,g,a,d,j,f,o);c!==e&&y.push(u(b)+":"+(j?" ":"")+c);A||(A=i)});b=A?j?"{\n"+f+y.join(",\n"+f)+"\n"+c+"}":"{"+y.join(",")+"}":"{}"}o.pop();return b}},q.stringify=function(b,c,a){var d,j,f,o,g,h;if(typeof c=="function"||
|
||||
typeof c=="object"&&c)if(l.call(c)=="[object Function]")j=c;else if(l.call(c)=="[object Array]"){f={};o=0;for(g=c.length;o<g;h=c[o++],(l.call(h)=="[object String]"||l.call(h)=="[object Number]")&&(f[h]=1));}if(a)if(l.call(a)=="[object Number]"){if((a=a-a%1)>0){d="";for(a>10&&(a=10);d.length<a;d=d+" ");}}else l.call(a)=="[object String]"&&(d=a.length<=10?a:a.slice(0,10));return x("",(h={},h[""]=b,h),j,f,d,"",[])});R("json-parse")||(z=String.fromCharCode,B={"\\":"\\",'"':'"',"/":"/",b:"\u0008",t:"\t",
|
||||
n:"\n",f:"\u000c",r:"\r"},C=function(){H=I=k;throw SyntaxError();},D=function(){for(var b=I,c=b.length,a,d,j,f,o;H<c;){a=b.charAt(H);if("\t\r\n ".indexOf(a)>-1)H++;else{if("{}[]:,".indexOf(a)>-1){H++;return a}if(a=='"'){d="@";for(H++;H<c;){a=b.charAt(H);if(a<" ")C();else if(a=="\\"){a=b.charAt(++H);if('\\"/btnfr'.indexOf(a)>-1){d=d+B[a];H++}else if(a=="u"){j=++H;for(f=H+4;H<f;H++){a=b.charAt(H);a>="0"&&a<="9"||a>="a"&&a<="f"||a>="A"&&a<="F"||C()}d=d+z("0x"+b.slice(j,H))}else C()}else{if(a=='"')break;
|
||||
d=d+a;H++}}if(b.charAt(H)=='"'){H++;return d}}else{j=H;if(a=="-"){o=i;a=b.charAt(++H)}if(a>="0"&&a<="9"){for(a=="0"&&(a=b.charAt(H+1),a>="0"&&a<="9")&&C();H<c&&(a=b.charAt(H),a>="0"&&a<="9");H++);if(b.charAt(H)=="."){for(f=++H;f<c&&(a=b.charAt(f),a>="0"&&a<="9");f++);f==H&&C();H=f}a=b.charAt(H);if(a=="e"||a=="E"){a=b.charAt(++H);(a=="+"||a=="-")&&H++;for(f=H;f<c&&(a=b.charAt(f),a>="0"&&a<="9");f++);f==H&&C();H=f}return+b.slice(j,H)}o&&C();if(b.slice(H,H+4)=="true"){H=H+4;return i}if(b.slice(H,H+5)==
|
||||
"false"){H=H+5;return false}if(b.slice(H,H+4)=="null"){H=H+4;return k}}C()}}return"$"},E=function(b){var c,a;b=="$"&&C();if(typeof b=="string"){if(b.charAt(0)=="@")return b.slice(1);if(b=="["){for(c=[];;a||(a=i)){b=D();if(b=="]")break;if(a)if(b==","){b=D();b=="]"&&C()}else C();b==","&&C();c.push(E(b))}return c}if(b=="{"){for(c={};;a||(a=i)){b=D();if(b=="}")break;if(a)if(b==","){b=D();b=="}"&&C()}else C();(b==","||typeof b!="string"||b.charAt(0)!="@"||D()!=":")&&C();c[b.slice(1)]=E(D())}return c}C()}return b},
|
||||
G=function(b,c,a){a=F(b,c,a);a===e?delete b[c]:b[c]=a},F=function(b,c,a){var d=b[c],j;if(typeof d=="object"&&d)if(l.call(d)=="[object Array]")for(j=d.length;j--;)G(d,j,a);else n(d,function(b){G(d,b,a)});return a.call(b,c,d)},q.parse=function(b,c){var a,d;H=0;I=b;a=E(D());D()!="$"&&C();H=I=k;return c&&l.call(c)=="[object Function]"?F((d={},d[""]=a,d),"",c):a})}p&&define(function(){return q});
|
||||
}());
|
||||
4
vendor/platform.js/platform.js
vendored
4
vendor/platform.js/platform.js
vendored
@@ -830,10 +830,10 @@
|
||||
};
|
||||
}
|
||||
// add browser/OS architecture
|
||||
if ((data = / (?:AMD|IA|Win|WOW|x86_|x)64\b/i.exec(arch)) && !/\bi686\b/i.test(arch)) {
|
||||
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(data, '');
|
||||
os.family = os.family.replace(RegExp(' *' + data), '');
|
||||
}
|
||||
if (name && (/WOW64/i.test(ua) ||
|
||||
(useFeatures && /\w(?:86|32)$/.test(nav.cpuClass || nav.platform)))) {
|
||||
|
||||
7
vendor/qunit-clib/qunit-clib.js
vendored
7
vendor/qunit-clib/qunit-clib.js
vendored
@@ -171,7 +171,12 @@
|
||||
|
||||
// exit out of Node.js
|
||||
try {
|
||||
process.exit();
|
||||
if (details.failed) {
|
||||
console.error('Error: ' + details.failed + ' of ' + details.total + ' tests failed.');
|
||||
process.exit(1);
|
||||
} else {
|
||||
process.exit(0);
|
||||
}
|
||||
} catch(e) { }
|
||||
}
|
||||
|
||||
|
||||
14
vendor/qunit/README.md
vendored
14
vendor/qunit/README.md
vendored
@@ -1,4 +1,4 @@
|
||||
[QUnit](http://docs.jquery.com/QUnit) - A JavaScript Unit Testing framework.
|
||||
[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
|
||||
@@ -35,7 +35,8 @@ the change, run `grunt` to lint and test it, then commit, push and create a pull
|
||||
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`.
|
||||
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
|
||||
--------
|
||||
@@ -47,3 +48,12 @@ tag, update them again to the next version, commit and push commits and tags
|
||||
|
||||
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):
|
||||
|
||||
scp -q qunit/qunit.js jqadmin@code.origin.jquery.com:/var/www/html/code.jquery.com/qunit/qunit-$version.js
|
||||
scp -q qunit/qunit.css jqadmin@code.origin.jquery.com:/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
|
||||
16
vendor/qunit/qunit/qunit.css
vendored
16
vendor/qunit/qunit/qunit.css
vendored
@@ -1,11 +1,11 @@
|
||||
/**
|
||||
* QUnit v1.9.0 - A JavaScript Unit Testing Framework
|
||||
* QUnit v1.10.0 - A JavaScript Unit Testing Framework
|
||||
*
|
||||
* http://docs.jquery.com/QUnit
|
||||
* http://qunitjs.com
|
||||
*
|
||||
* Copyright (c) 2012 John Resig, Jörn Zaefferer
|
||||
* Dual licensed under the MIT (MIT-LICENSE.txt)
|
||||
* or GPL (GPL-LICENSE.txt) licenses.
|
||||
* Copyright 2012 jQuery Foundation and other contributors
|
||||
* Released under the MIT license.
|
||||
* http://jquery.org/license
|
||||
*/
|
||||
|
||||
/** Font Family and Sizes */
|
||||
@@ -20,7 +20,7 @@
|
||||
|
||||
/** Resets */
|
||||
|
||||
#qunit-tests, #qunit-tests ol, #qunit-header, #qunit-banner, #qunit-userAgent, #qunit-testresult {
|
||||
#qunit-tests, #qunit-tests ol, #qunit-header, #qunit-banner, #qunit-userAgent, #qunit-testresult, #qunit-modulefilter {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
@@ -67,6 +67,7 @@
|
||||
padding: 0.5em 0 0.5em 2em;
|
||||
color: #5E740B;
|
||||
background-color: #eee;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
#qunit-userAgent {
|
||||
@@ -76,6 +77,9 @@
|
||||
text-shadow: rgba(0, 0, 0, 0.5) 2px 2px 1px;
|
||||
}
|
||||
|
||||
#qunit-modulefilter-container {
|
||||
float: right;
|
||||
}
|
||||
|
||||
/** Tests: Pass/Fail */
|
||||
|
||||
|
||||
89
vendor/qunit/qunit/qunit.js
vendored
89
vendor/qunit/qunit/qunit.js
vendored
@@ -1,11 +1,11 @@
|
||||
/**
|
||||
* QUnit v1.9.0 - A JavaScript Unit Testing Framework
|
||||
* QUnit v1.10.0 - A JavaScript Unit Testing Framework
|
||||
*
|
||||
* http://docs.jquery.com/QUnit
|
||||
* http://qunitjs.com
|
||||
*
|
||||
* Copyright (c) 2012 John Resig, Jörn Zaefferer
|
||||
* Dual licensed under the MIT (MIT-LICENSE.txt)
|
||||
* or GPL (GPL-LICENSE.txt) licenses.
|
||||
* Copyright 2012 jQuery Foundation and other contributors
|
||||
* Released under the MIT license.
|
||||
* http://jquery.org/license
|
||||
*/
|
||||
|
||||
(function( window ) {
|
||||
@@ -17,6 +17,8 @@ var QUnit,
|
||||
fileName = (sourceFromStacktrace( 0 ) || "" ).replace(/(:\d+)+\)?/, "").replace(/.+\//, ""),
|
||||
toString = Object.prototype.toString,
|
||||
hasOwn = Object.prototype.hasOwnProperty,
|
||||
// Keep a local reference to Date (GH-283)
|
||||
Date = window.Date,
|
||||
defined = {
|
||||
setTimeout: typeof window.setTimeout !== "undefined",
|
||||
sessionStorage: (function() {
|
||||
@@ -304,7 +306,8 @@ QUnit = {
|
||||
// call on start of module test to prepend name to all tests
|
||||
module: function( name, testEnvironment ) {
|
||||
config.currentModule = name;
|
||||
config.currentModuleTestEnviroment = testEnvironment;
|
||||
config.currentModuleTestEnvironment = testEnvironment;
|
||||
config.modules[name] = true;
|
||||
},
|
||||
|
||||
asyncTest: function( testName, expected, callback ) {
|
||||
@@ -336,7 +339,7 @@ QUnit = {
|
||||
async: async,
|
||||
callback: callback,
|
||||
module: config.currentModule,
|
||||
moduleTestEnvironment: config.currentModuleTestEnviroment,
|
||||
moduleTestEnvironment: config.currentModuleTestEnvironment,
|
||||
stack: sourceFromStacktrace( 2 )
|
||||
});
|
||||
|
||||
@@ -349,7 +352,11 @@ QUnit = {
|
||||
|
||||
// Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through.
|
||||
expect: function( asserts ) {
|
||||
config.current.expected = asserts;
|
||||
if (arguments.length === 1) {
|
||||
config.current.expected = asserts;
|
||||
} else {
|
||||
return config.current.expected;
|
||||
}
|
||||
},
|
||||
|
||||
start: function( count ) {
|
||||
@@ -415,6 +422,8 @@ QUnit.assert = {
|
||||
|
||||
var source,
|
||||
details = {
|
||||
module: config.current.module,
|
||||
name: config.current.testName,
|
||||
result: result,
|
||||
message: msg
|
||||
};
|
||||
@@ -600,6 +609,9 @@ config = {
|
||||
}
|
||||
],
|
||||
|
||||
// Set of all modules.
|
||||
modules: {},
|
||||
|
||||
// logging callback queues
|
||||
begin: [],
|
||||
done: [],
|
||||
@@ -710,17 +722,10 @@ extend( QUnit, {
|
||||
},
|
||||
|
||||
// Resets the test setup. Useful for tests that modify the DOM.
|
||||
// If jQuery is available, uses jQuery's html(), otherwise just innerHTML.
|
||||
reset: function() {
|
||||
var fixture;
|
||||
|
||||
if ( window.jQuery ) {
|
||||
jQuery( "#qunit-fixture" ).html( config.fixture );
|
||||
} else {
|
||||
fixture = id( "qunit-fixture" );
|
||||
if ( fixture ) {
|
||||
fixture.innerHTML = config.fixture;
|
||||
}
|
||||
var fixture = id( "qunit-fixture" );
|
||||
if ( fixture ) {
|
||||
fixture.innerHTML = config.fixture;
|
||||
}
|
||||
},
|
||||
|
||||
@@ -781,6 +786,8 @@ extend( QUnit, {
|
||||
|
||||
var output, source,
|
||||
details = {
|
||||
module: config.current.module,
|
||||
name: config.current.testName,
|
||||
result: result,
|
||||
message: message,
|
||||
actual: actual,
|
||||
@@ -826,6 +833,8 @@ extend( QUnit, {
|
||||
|
||||
var output,
|
||||
details = {
|
||||
module: config.current.module,
|
||||
name: config.current.testName,
|
||||
result: false,
|
||||
message: message
|
||||
};
|
||||
@@ -916,7 +925,9 @@ QUnit.load = function() {
|
||||
runLoggingCallbacks( "begin", QUnit, {} );
|
||||
|
||||
// Initialize the config, saving the execution queue
|
||||
var banner, filter, i, label, len, main, ol, toolbar, userAgent, val, urlConfigCheckboxes,
|
||||
var banner, filter, i, label, len, main, ol, toolbar, userAgent, val, urlConfigCheckboxes, moduleFilter,
|
||||
numModules = 0,
|
||||
moduleFilterHtml = "",
|
||||
urlConfigHtml = "",
|
||||
oldconfig = extend( {}, config );
|
||||
|
||||
@@ -940,6 +951,15 @@ QUnit.load = function() {
|
||||
urlConfigHtml += "<input id='qunit-urlconfig-" + val.id + "' name='" + val.id + "' type='checkbox'" + ( config[ val.id ] ? " checked='checked'" : "" ) + " title='" + val.tooltip + "'><label for='qunit-urlconfig-" + val.id + "' title='" + val.tooltip + "'>" + val.label + "</label>";
|
||||
}
|
||||
|
||||
moduleFilterHtml += "<label for='qunit-modulefilter'>Module: </label><select id='qunit-modulefilter' name='modulefilter'><option value='' " + ( config.module === undefined ? "selected" : "" ) + ">< All Modules ></option>";
|
||||
for ( i in config.modules ) {
|
||||
if ( config.modules.hasOwnProperty( i ) ) {
|
||||
numModules += 1;
|
||||
moduleFilterHtml += "<option value='" + encodeURIComponent(i) + "' " + ( config.module === i ? "selected" : "" ) + ">" + i + "</option>";
|
||||
}
|
||||
}
|
||||
moduleFilterHtml += "</select>";
|
||||
|
||||
// `userAgent` initialized at top of scope
|
||||
userAgent = id( "qunit-userAgent" );
|
||||
if ( userAgent ) {
|
||||
@@ -1002,6 +1022,19 @@ QUnit.load = function() {
|
||||
window.location = QUnit.url( params );
|
||||
});
|
||||
toolbar.appendChild( urlConfigCheckboxes );
|
||||
|
||||
if (numModules > 1) {
|
||||
moduleFilter = document.createElement( 'span' );
|
||||
moduleFilter.setAttribute( 'id', 'qunit-modulefilter-container' );
|
||||
moduleFilter.innerHTML = moduleFilterHtml;
|
||||
addEvent( moduleFilter, "change", function() {
|
||||
var selectBox = moduleFilter.getElementsByTagName("select")[0],
|
||||
selectedModule = decodeURIComponent(selectBox.options[selectBox.selectedIndex].value);
|
||||
|
||||
window.location = QUnit.url( { module: ( selectedModule === "" ) ? undefined : selectedModule } );
|
||||
});
|
||||
toolbar.appendChild(moduleFilter);
|
||||
}
|
||||
}
|
||||
|
||||
// `main` initialized at top of scope
|
||||
@@ -1039,9 +1072,9 @@ window.onerror = function ( error, filePath, linerNr ) {
|
||||
}
|
||||
QUnit.pushFailure( error, filePath + ":" + linerNr );
|
||||
} else {
|
||||
QUnit.test( "global failure", function() {
|
||||
QUnit.test( "global failure", extend( function() {
|
||||
QUnit.pushFailure( error, filePath + ":" + linerNr );
|
||||
});
|
||||
}, { validTest: validTest } ) );
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -1108,6 +1141,11 @@ function done() {
|
||||
}
|
||||
}
|
||||
|
||||
// scroll back to top to show results
|
||||
if ( window.scrollTo ) {
|
||||
window.scrollTo(0, 0);
|
||||
}
|
||||
|
||||
runLoggingCallbacks( "done", QUnit, {
|
||||
failed: config.stats.bad,
|
||||
passed: passed,
|
||||
@@ -1123,6 +1161,12 @@ function validTest( test ) {
|
||||
module = config.module && config.module.toLowerCase(),
|
||||
fullName = (test.module + ": " + test.testName).toLowerCase();
|
||||
|
||||
// Internally-generated tests are always valid
|
||||
if ( test.callback && test.callback.validTest === validTest ) {
|
||||
delete test.callback.validTest;
|
||||
return true;
|
||||
}
|
||||
|
||||
if ( config.testNumber ) {
|
||||
return test.testNumber === config.testNumber;
|
||||
}
|
||||
@@ -1404,7 +1448,8 @@ QUnit.equiv = (function() {
|
||||
a.global === b.global &&
|
||||
// (gmi) ...
|
||||
a.ignoreCase === b.ignoreCase &&
|
||||
a.multiline === b.multiline;
|
||||
a.multiline === b.multiline &&
|
||||
a.sticky === b.sticky;
|
||||
},
|
||||
|
||||
// - skip when the property is a method of an instance (OOP)
|
||||
|
||||
734
vendor/requirejs/require.js
vendored
734
vendor/requirejs/require.js
vendored
File diff suppressed because it is too large
Load Diff
62
vendor/underscore/test/arrays.js
vendored
62
vendor/underscore/test/arrays.js
vendored
@@ -2,7 +2,7 @@ $(document).ready(function() {
|
||||
|
||||
module("Arrays");
|
||||
|
||||
test("arrays: first", function() {
|
||||
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()"');
|
||||
equal(_.first([1,2,3], 0).join(', '), "", 'can pass an index to first');
|
||||
@@ -14,9 +14,11 @@ $(document).ready(function() {
|
||||
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');
|
||||
});
|
||||
|
||||
test("arrays: rest", function() {
|
||||
test("rest", function() {
|
||||
var numbers = [1, 2, 3, 4];
|
||||
equal(_.rest(numbers).join(", "), "2, 3, 4", 'working rest()');
|
||||
equal(_.rest(numbers, 0).join(", "), "1, 2, 3, 4", 'working rest(0)');
|
||||
@@ -25,9 +27,11 @@ $(document).ready(function() {
|
||||
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("arrays: initial", function() {
|
||||
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);
|
||||
@@ -36,7 +40,7 @@ $(document).ready(function() {
|
||||
equal(_.flatten(result).join(','), '1,2,1,2', 'initial works with _.map');
|
||||
});
|
||||
|
||||
test("arrays: last", function() {
|
||||
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');
|
||||
@@ -45,15 +49,17 @@ $(document).ready(function() {
|
||||
equal(result, 4, 'works on an arguments object');
|
||||
result = _.map([[1,2,3],[1,2,3]], _.last);
|
||||
equal(result.join(','), '3,3', 'works well with _.map');
|
||||
|
||||
equal(_.last(null), undefined, 'handles nulls');
|
||||
});
|
||||
|
||||
test("arrays: 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 _(arguments).compact().length; })(0, 1, false, 2, false, 3);
|
||||
equal(result, 3, 'works on an arguments object');
|
||||
});
|
||||
|
||||
test("arrays: flatten", function() {
|
||||
test("flatten", function() {
|
||||
if (window.JSON) {
|
||||
var list = [1, [2], [3, [[[4]]]]];
|
||||
equal(JSON.stringify(_.flatten(list)), '[1,2,3,4]', 'can flatten nested arrays');
|
||||
@@ -63,7 +69,7 @@ $(document).ready(function() {
|
||||
}
|
||||
});
|
||||
|
||||
test("arrays: without", function() {
|
||||
test("without", function() {
|
||||
var list = [1, 2, 1, 0, 3, 1, 4];
|
||||
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);
|
||||
@@ -74,7 +80,7 @@ $(document).ready(function() {
|
||||
ok(_.without(list, list[0]).length == 1, 'ditto.');
|
||||
});
|
||||
|
||||
test("arrays: uniq", function() {
|
||||
test("uniq", function() {
|
||||
var list = [1, 2, 1, 3, 1, 4];
|
||||
equal(_.uniq(list).join(', '), '1, 2, 3, 4', 'can find the unique values of an unsorted array');
|
||||
|
||||
@@ -93,7 +99,7 @@ $(document).ready(function() {
|
||||
equal(result.join(', '), '1, 2, 3, 4', 'works on an arguments object');
|
||||
});
|
||||
|
||||
test("arrays: intersection", function() {
|
||||
test("intersection", function() {
|
||||
var stooges = ['moe', 'curly', 'larry'], leaders = ['moe', 'groucho'];
|
||||
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');
|
||||
@@ -101,7 +107,7 @@ $(document).ready(function() {
|
||||
equal(result.join(''), 'moe', 'works on an arguments object');
|
||||
});
|
||||
|
||||
test("arrays: union", function() {
|
||||
test("union", function() {
|
||||
var result = _.union([1, 2, 3], [2, 30, 1], [1, 40]);
|
||||
equal(result.join(' '), '1 2 3 30 40', 'takes the union of a list of arrays');
|
||||
|
||||
@@ -109,7 +115,7 @@ $(document).ready(function() {
|
||||
equal(result.join(' '), '1 2 3 30 40 1', 'takes the union of a list of nested arrays');
|
||||
});
|
||||
|
||||
test("arrays: difference", function() {
|
||||
test("difference", function() {
|
||||
var result = _.difference([1, 2, 3], [2, 30, 40]);
|
||||
equal(result.join(' '), '1 3', 'takes the difference of two arrays');
|
||||
|
||||
@@ -117,19 +123,28 @@ $(document).ready(function() {
|
||||
equal(result.join(' '), '3 4', 'takes the difference of three arrays');
|
||||
});
|
||||
|
||||
test('arrays: zip', function() {
|
||||
test('zip', function() {
|
||||
var names = ['moe', 'larry', 'curly'], ages = [30, 40, 50], leaders = [true];
|
||||
var stooges = _.zip(names, ages, leaders);
|
||||
equal(String(stooges), 'moe,30,true,larry,40,,curly,50,', 'zipped together arrays of different lengths');
|
||||
});
|
||||
|
||||
test('arrays: zipObject', function() {
|
||||
var result = _.zipObject(['moe', 'larry', 'curly'], [30, 40, 50]);
|
||||
test('object', function() {
|
||||
var result = _.object(['moe', 'larry', 'curly'], [30, 40, 50]);
|
||||
var shouldBe = {moe: 30, larry: 40, curly: 50};
|
||||
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};
|
||||
ok(_.isEqual(result, shouldBe), 'an array of pairs zipped together into an object');
|
||||
|
||||
var stooges = {moe: 30, larry: 40, curly: 50};
|
||||
ok(_.isEqual(_.object(_.pairs(stooges)), stooges), 'an object converted to pairs and back to an object');
|
||||
|
||||
ok(_.isEqual(_.object(null), {}), 'handles nulls');
|
||||
});
|
||||
|
||||
test("arrays: indexOf", function() {
|
||||
test("indexOf", function() {
|
||||
var numbers = [1, 2, 3];
|
||||
numbers.indexOf = null;
|
||||
equal(_.indexOf(numbers, 2), 1, 'can compute indexOf, even without the native function');
|
||||
@@ -148,19 +163,30 @@ $(document).ready(function() {
|
||||
numbers = [1, 40, 40, 40, 40, 40, 40, 40, 50, 60, 70]; num = 40;
|
||||
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');
|
||||
});
|
||||
|
||||
test("arrays: lastIndexOf", function() {
|
||||
var numbers = [1, 0, 1, 0, 0, 1, 0, 0, 0];
|
||||
test("lastIndexOf", function() {
|
||||
var numbers = [1, 0, 1];
|
||||
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);
|
||||
equal(result, 5, 'works on an arguments object');
|
||||
equal(_.indexOf(null, 2), -1, 'handles nulls properly');
|
||||
|
||||
numbers = [1, 2, 3, 1, 2, 3, 1, 2, 3];
|
||||
index = _.lastIndexOf(numbers, 2, 2);
|
||||
equal(index, 1, 'supports the fromIndex argument');
|
||||
});
|
||||
|
||||
test("arrays: range", function() {
|
||||
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 & b, a<b generates an array of elements a,a+1,a+2,...,b-2,b-1');
|
||||
|
||||
8
vendor/underscore/test/chaining.js
vendored
8
vendor/underscore/test/chaining.js
vendored
@@ -2,7 +2,7 @@ $(document).ready(function() {
|
||||
|
||||
module("Chaining");
|
||||
|
||||
test("chaining: 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",
|
||||
@@ -20,7 +20,7 @@ $(document).ready(function() {
|
||||
ok(counts['a'] == 16 && counts['e'] == 10, 'counted all the letters in the song');
|
||||
});
|
||||
|
||||
test("chaining: select/reject/sortBy", function() {
|
||||
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;
|
||||
@@ -32,7 +32,7 @@ $(document).ready(function() {
|
||||
equal(numbers.join(', '), "10, 6, 2", "filtered and reversed the numbers");
|
||||
});
|
||||
|
||||
test("chaining: select/reject/sortBy in functional style", function() {
|
||||
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;
|
||||
@@ -44,7 +44,7 @@ $(document).ready(function() {
|
||||
equal(numbers.join(', '), "10, 6, 2", "filtered and reversed the numbers");
|
||||
});
|
||||
|
||||
test("chaining: reverse/concat/unshift/pop/map", function() {
|
||||
test("reverse/concat/unshift/pop/map", function() {
|
||||
var numbers = [1,2,3,4,5];
|
||||
numbers = _(numbers).chain()
|
||||
.reverse()
|
||||
|
||||
184
vendor/underscore/test/collections.js
vendored
184
vendor/underscore/test/collections.js
vendored
@@ -2,7 +2,7 @@ $(document).ready(function() {
|
||||
|
||||
module("Collections");
|
||||
|
||||
test("collections: each", function() {
|
||||
test("each", function() {
|
||||
_.each([1, 2, 3], function(num, i) {
|
||||
equal(num, i + 1, 'each iterators provide value and iteration count');
|
||||
});
|
||||
@@ -31,7 +31,7 @@ $(document).ready(function() {
|
||||
equal(answers, 0, 'handles a null properly');
|
||||
});
|
||||
|
||||
test('collections: map', function() {
|
||||
test('map', function() {
|
||||
var doubled = _.map([1, 2, 3], function(num){ return num * 2; });
|
||||
equal(doubled.join(', '), '2, 4, 6', 'doubled numbers');
|
||||
|
||||
@@ -44,8 +44,13 @@ $(document).ready(function() {
|
||||
var doubled = _([1, 2, 3]).map(function(num){ return num * 2; });
|
||||
equal(doubled.join(', '), '2, 4, 6', 'OO-style doubled numbers');
|
||||
|
||||
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.');
|
||||
}
|
||||
|
||||
var ids = _.map($('#map-test').children(), function(n){ return n.id; });
|
||||
deepEqual(ids, ['id1', 'id2'], 'Can use collection methods on NodeLists.');
|
||||
deepEqual(ids, ['id1', 'id2'], 'Can use collection methods on jQuery Array-likes.');
|
||||
|
||||
var ids = _.map(document.images, function(n){ return n.id; });
|
||||
ok(ids[0] == 'chart_image', 'can use collection methods on HTMLCollections');
|
||||
@@ -54,7 +59,7 @@ $(document).ready(function() {
|
||||
ok(_.isArray(ifnull) && ifnull.length === 0, 'handles a null properly');
|
||||
});
|
||||
|
||||
test('collections: reduce', function() {
|
||||
test('reduce', function() {
|
||||
var sum = _.reduce([1, 2, 3], function(sum, num){ return sum + num; }, 0);
|
||||
equal(sum, 6, 'can sum up an array');
|
||||
|
||||
@@ -84,7 +89,7 @@ $(document).ready(function() {
|
||||
raises(function() { _.reduce([], function(){}); }, TypeError, 'throws an error for empty arrays with no initial value');
|
||||
});
|
||||
|
||||
test('collections: reduceRight', function() {
|
||||
test('reduceRight', function() {
|
||||
var list = _.reduceRight(["foo", "bar", "baz"], function(memo, str){ return memo + str; }, '');
|
||||
equal(list, 'bazbarfoo', 'can perform right folds');
|
||||
|
||||
@@ -102,24 +107,60 @@ $(document).ready(function() {
|
||||
}
|
||||
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, function(){}, 138) === 138, 'handles a null (with initial value) properly');
|
||||
|
||||
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.
|
||||
|
||||
var args,
|
||||
memo = {},
|
||||
object = {a: 1, b: 2},
|
||||
lastKey = _.keys(object).pop();
|
||||
|
||||
var expected = lastKey == 'a'
|
||||
? [memo, 1, 'a', object]
|
||||
: [memo, 2, 'b', object];
|
||||
|
||||
_.reduceRight(object, function() {
|
||||
args || (args = _.toArray(arguments));
|
||||
}, memo);
|
||||
|
||||
deepEqual(args, expected);
|
||||
|
||||
// And again, with numeric keys.
|
||||
|
||||
object = {'2': 'a', '1': 'b'};
|
||||
lastKey = _.keys(object).pop();
|
||||
args = null;
|
||||
|
||||
expected = lastKey == '2'
|
||||
? [memo, 'a', '2', object]
|
||||
: [memo, 'b', '1', object];
|
||||
|
||||
_.reduceRight(object, function() {
|
||||
args || (args = _.toArray(arguments));
|
||||
}, memo);
|
||||
|
||||
deepEqual(args, expected);
|
||||
});
|
||||
|
||||
test('collections: find', function() {
|
||||
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');
|
||||
});
|
||||
|
||||
test('collections: detect', function() {
|
||||
test('detect', function() {
|
||||
var result = _.detect([1, 2, 3], function(num){ return num * 2 == 4; });
|
||||
equal(result, 2, 'found the first "2" and broke the loop');
|
||||
});
|
||||
|
||||
test('collections: select', function() {
|
||||
test('select', function() {
|
||||
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');
|
||||
|
||||
@@ -127,12 +168,20 @@ $(document).ready(function() {
|
||||
equal(evens.join(', '), '2, 4, 6', 'aliased as "filter"');
|
||||
});
|
||||
|
||||
test('collections: reject', function() {
|
||||
test('reject', function() {
|
||||
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 evens = _.reject([1, 2, 3, 4, 5, 6], function(num){
|
||||
equal(context, "obj");
|
||||
return num % 2 != 0;
|
||||
}, context);
|
||||
equal(evens.join(', '), '2, 4, 6', 'rejected each odd number');
|
||||
});
|
||||
|
||||
test('collections: all', function() {
|
||||
test('all', function() {
|
||||
ok(_.all([], _.identity), 'the empty set');
|
||||
ok(_.all([true, true, true], _.identity), 'all true values');
|
||||
ok(!_.all([true, false, true], _.identity), 'one false value');
|
||||
@@ -141,9 +190,10 @@ $(document).ready(function() {
|
||||
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('collections: any', function() {
|
||||
test('any', function() {
|
||||
var nativeSome = Array.prototype.some;
|
||||
Array.prototype.some = null;
|
||||
ok(!_.any([]), 'the empty set');
|
||||
@@ -159,21 +209,21 @@ $(document).ready(function() {
|
||||
Array.prototype.some = nativeSome;
|
||||
});
|
||||
|
||||
test('collections: include', function() {
|
||||
test('include', function() {
|
||||
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('collections: invoke', function() {
|
||||
test('invoke', function() {
|
||||
var list = [[5, 1, 7], [3, 2, 1]];
|
||||
var result = _.invoke(list, 'sort');
|
||||
equal(result[0].join(', '), '1, 5, 7', 'first array sorted');
|
||||
equal(result[1].join(', '), '1, 2, 3', 'second array sorted');
|
||||
});
|
||||
|
||||
test('collections: invoke w/ function reference', function() {
|
||||
test('invoke w/ function reference', function() {
|
||||
var list = [[5, 1, 7], [3, 2, 1]];
|
||||
var result = _.invoke(list, Array.prototype.sort);
|
||||
equal(result[0].join(', '), '1, 5, 7', 'first array sorted');
|
||||
@@ -181,7 +231,7 @@ $(document).ready(function() {
|
||||
});
|
||||
|
||||
// Relevant when using ClojureScript
|
||||
test('collections: invoke when strings have a call method', function() {
|
||||
test('invoke when strings have a call method', function() {
|
||||
String.prototype.call = function() {
|
||||
return 42;
|
||||
};
|
||||
@@ -195,12 +245,22 @@ $(document).ready(function() {
|
||||
equal(s.call, undefined, "call function removed");
|
||||
});
|
||||
|
||||
test('collections: pluck', function() {
|
||||
test('pluck', function() {
|
||||
var people = [{name : 'moe', age : 30}, {name : 'curly', age : 50}];
|
||||
equal(_.pluck(people, 'name').join(', '), 'moe, curly', 'pulls names out of objects');
|
||||
});
|
||||
|
||||
test('collections: max', function() {
|
||||
test('where', function() {
|
||||
var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}];
|
||||
var result = _.where(list, {a: 1});
|
||||
equal(result.length, 3);
|
||||
equal(result[result.length - 1].b, 4);
|
||||
result = _.where(list, {b: 2});
|
||||
equal(result.length, 2);
|
||||
equal(result[0].a, 1);
|
||||
});
|
||||
|
||||
test('max', function() {
|
||||
equal(3, _.max([1, 2, 3]), 'can perform a regular Math.max');
|
||||
|
||||
var neg = _.max([1, 2, 3], function(num){ return -num; });
|
||||
@@ -212,7 +272,7 @@ $(document).ready(function() {
|
||||
equal(299999, _.max(_.range(1,300000)), "Maximum value of a too-big array");
|
||||
});
|
||||
|
||||
test('collections: min', function() {
|
||||
test('min', function() {
|
||||
equal(1, _.min([1, 2, 3]), 'can perform a regular Math.min');
|
||||
|
||||
var neg = _.min([1, 2, 3], function(num){ return -num; });
|
||||
@@ -228,7 +288,7 @@ $(document).ready(function() {
|
||||
equal(1, _.min(_.range(1,300000)), "Minimum value of a too-big array");
|
||||
});
|
||||
|
||||
test('collections: sortBy', function() {
|
||||
test('sortBy', function() {
|
||||
var people = [{name : 'curly', age : 50}, {name : 'moe', age : 30}];
|
||||
people = _.sortBy(people, function(person){ return person.age; });
|
||||
equal(_.pluck(people, 'name').join(', '), 'moe, curly', 'stooges sorted by age');
|
||||
@@ -239,9 +299,32 @@ $(document).ready(function() {
|
||||
var list = ["one", "two", "three", "four", "five"];
|
||||
var sorted = _.sortBy(list, 'length');
|
||||
equal(sorted.join(' '), 'one two four five three', 'sorted by length');
|
||||
|
||||
function Pair(x, y) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
|
||||
var collection = [
|
||||
new Pair(1, 1), new Pair(1, 2),
|
||||
new Pair(1, 3), new Pair(1, 4),
|
||||
new Pair(1, 5), new Pair(1, 6),
|
||||
new Pair(2, 1), new Pair(2, 2),
|
||||
new Pair(2, 3), new Pair(2, 4),
|
||||
new Pair(2, 5), new Pair(2, 6),
|
||||
new Pair(undefined, 1), new Pair(undefined, 2),
|
||||
new Pair(undefined, 3), new Pair(undefined, 4),
|
||||
new Pair(undefined, 5), new Pair(undefined, 6)
|
||||
];
|
||||
|
||||
var actual = _.sortBy(collection, function(pair) {
|
||||
return pair.x;
|
||||
});
|
||||
|
||||
deepEqual(actual, collection, 'sortBy should be stable');
|
||||
});
|
||||
|
||||
test('collections: groupBy', function() {
|
||||
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');
|
||||
equal(parity[0].join(', '), '2, 4, 6', 'put each even number in the right group');
|
||||
@@ -251,9 +334,21 @@ $(document).ready(function() {
|
||||
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);
|
||||
|
||||
grouped = _.groupBy([4.2, 6.1, 6.4], function(num) {
|
||||
return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor';
|
||||
});
|
||||
equal(grouped.constructor.length, 1);
|
||||
equal(grouped.hasOwnProperty.length, 2);
|
||||
|
||||
var array = [{}];
|
||||
_.groupBy(array, function(value, index, obj){ ok(obj === array); });
|
||||
});
|
||||
|
||||
test('collections: countBy', function() {
|
||||
test('countBy', function() {
|
||||
var parity = _.countBy([1, 2, 3, 4, 5], function(num){ return num % 2 == 0; });
|
||||
equal(parity['true'], 2);
|
||||
equal(parity['false'], 3);
|
||||
@@ -263,25 +358,46 @@ $(document).ready(function() {
|
||||
equal(grouped['3'], 4);
|
||||
equal(grouped['4'], 3);
|
||||
equal(grouped['5'], 3);
|
||||
|
||||
var context = {};
|
||||
_.countBy([{}], function(){ ok(this === context); }, context);
|
||||
|
||||
grouped = _.countBy([4.2, 6.1, 6.4], function(num) {
|
||||
return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor';
|
||||
});
|
||||
equal(grouped.constructor, 1);
|
||||
equal(grouped.hasOwnProperty, 2);
|
||||
|
||||
var array = [{}];
|
||||
_.countBy(array, function(value, index, obj){ ok(obj === array); });
|
||||
});
|
||||
|
||||
test('collections: sortedIndex', function() {
|
||||
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);
|
||||
});
|
||||
|
||||
test('collections: shuffle', function() {
|
||||
test('shuffle', function() {
|
||||
var numbers = _.range(10);
|
||||
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('collections: toArray', function() {
|
||||
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];
|
||||
@@ -290,19 +406,21 @@ $(document).ready(function() {
|
||||
|
||||
var numbers = _.toArray({one : 1, two : 2, three : 3});
|
||||
equal(numbers.join(', '), '1, 2, 3', 'object flattened into array');
|
||||
|
||||
var objectWithToArrayFunction = {toArray: function() {
|
||||
return [1, 2, 3];
|
||||
}};
|
||||
equal(_.toArray(objectWithToArrayFunction).join(', '), '1, 2, 3', 'toArray method used if present');
|
||||
|
||||
var objectWithToArrayValue = {toArray: 1};
|
||||
equal(_.toArray(objectWithToArrayValue).join(', '), '1', 'toArray property ignored if not a function');
|
||||
});
|
||||
|
||||
test('collections: size', function() {
|
||||
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');
|
||||
|
||||
var func = function() {
|
||||
return _.size(arguments);
|
||||
};
|
||||
|
||||
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');
|
||||
|
||||
equal(_.size(null), 0, 'handles nulls');
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
69
vendor/underscore/test/functions.js
vendored
69
vendor/underscore/test/functions.js
vendored
@@ -2,7 +2,7 @@ $(document).ready(function() {
|
||||
|
||||
module("Functions");
|
||||
|
||||
test("functions: bind", function() {
|
||||
test("bind", function() {
|
||||
var context = {name : 'moe'};
|
||||
var func = function(arg) { return "name: " + (this.name || arg); };
|
||||
var bound = _.bind(func, context);
|
||||
@@ -38,7 +38,7 @@ $(document).ready(function() {
|
||||
equal(Boundf().hello, "moe curly", "When called without the new operator, it's OK to be bound to the context");
|
||||
});
|
||||
|
||||
test("functions: bindAll", function() {
|
||||
test("bindAll", function() {
|
||||
var curly = {name : 'curly'}, moe = {
|
||||
name : 'moe',
|
||||
getName : function() { return 'name: ' + this.name; },
|
||||
@@ -61,7 +61,7 @@ $(document).ready(function() {
|
||||
equal(curly.sayHi(), 'hi: moe', 'calling bindAll with no arguments binds all functions to the object');
|
||||
});
|
||||
|
||||
test("functions: memoize", function() {
|
||||
test("memoize", function() {
|
||||
var fib = function(n) {
|
||||
return n < 2 ? n : fib(n - 1) + fib(n - 2);
|
||||
};
|
||||
@@ -77,20 +77,20 @@ $(document).ready(function() {
|
||||
equal(fastO('toString'), 'toString', 'checks hasOwnProperty');
|
||||
});
|
||||
|
||||
asyncTest("functions: 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("functions: 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);
|
||||
});
|
||||
|
||||
asyncTest("functions: throttle", 2, function() {
|
||||
asyncTest("throttle", 2, function() {
|
||||
var counter = 0;
|
||||
var incr = function(){ counter++; };
|
||||
var throttledIncr = _.throttle(incr, 100);
|
||||
@@ -105,7 +105,7 @@ $(document).ready(function() {
|
||||
_.delay(function(){ equal(counter, 4, "incr was throttled"); start(); }, 400);
|
||||
});
|
||||
|
||||
asyncTest("functions: throttle arguments", 2, function() {
|
||||
asyncTest("throttle arguments", 2, function() {
|
||||
var value = 0;
|
||||
var update = function(val){ value = val; };
|
||||
var throttledUpdate = _.throttle(update, 100);
|
||||
@@ -117,7 +117,7 @@ $(document).ready(function() {
|
||||
_.delay(function(){ equal(value, 6, "updated to latest value"); start(); }, 400);
|
||||
});
|
||||
|
||||
asyncTest("functions: throttle once", 2, function() {
|
||||
asyncTest("throttle once", 2, function() {
|
||||
var counter = 0;
|
||||
var incr = function(){ return ++counter; };
|
||||
var throttledIncr = _.throttle(incr, 100);
|
||||
@@ -128,7 +128,7 @@ $(document).ready(function() {
|
||||
}, 220);
|
||||
});
|
||||
|
||||
asyncTest("functions: throttle twice", 1, function() {
|
||||
asyncTest("throttle twice", 1, function() {
|
||||
var counter = 0;
|
||||
var incr = function(){ counter++; };
|
||||
var throttledIncr = _.throttle(incr, 100);
|
||||
@@ -136,7 +136,34 @@ $(document).ready(function() {
|
||||
_.delay(function(){ equal(counter, 2, "incr was called twice"); start(); }, 220);
|
||||
});
|
||||
|
||||
asyncTest("functions: debounce", 1, function() {
|
||||
asyncTest("throttle repeatedly with results", 9, function() {
|
||||
var counter = 0;
|
||||
var incr = function(){ return ++counter; };
|
||||
var throttledIncr = _.throttle(incr, 100);
|
||||
var results = [];
|
||||
var saveResult = function() { results.push(throttledIncr()); };
|
||||
saveResult(); saveResult(); saveResult();
|
||||
setTimeout(saveResult, 70);
|
||||
setTimeout(saveResult, 120);
|
||||
setTimeout(saveResult, 140);
|
||||
setTimeout(saveResult, 190);
|
||||
setTimeout(saveResult, 240);
|
||||
setTimeout(saveResult, 260);
|
||||
_.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], 1, "incr was throttled");
|
||||
equal(results[4], 2, "incr was called twice");
|
||||
equal(results[5], 2, "incr was throttled");
|
||||
equal(results[6], 2, "incr was throttled");
|
||||
equal(results[7], 3, "incr was called thrice");
|
||||
equal(results[8], 3, "incr was throttled");
|
||||
start();
|
||||
}, 400);
|
||||
});
|
||||
|
||||
asyncTest("debounce", 1, function() {
|
||||
var counter = 0;
|
||||
var incr = function(){ counter++; };
|
||||
var debouncedIncr = _.debounce(incr, 50);
|
||||
@@ -149,11 +176,17 @@ $(document).ready(function() {
|
||||
_.delay(function(){ equal(counter, 1, "incr was debounced"); start(); }, 220);
|
||||
});
|
||||
|
||||
asyncTest("functions: debounce asap", 2, function() {
|
||||
asyncTest("debounce asap", 5, function() {
|
||||
var a, b, c;
|
||||
var counter = 0;
|
||||
var incr = function(){ counter++; };
|
||||
var incr = function(){ return ++counter; };
|
||||
var debouncedIncr = _.debounce(incr, 50, true);
|
||||
debouncedIncr(); debouncedIncr(); debouncedIncr();
|
||||
a = debouncedIncr();
|
||||
b = debouncedIncr();
|
||||
c = debouncedIncr();
|
||||
equal(a, 1);
|
||||
equal(b, 1);
|
||||
equal(c, 1);
|
||||
equal(counter, 1, 'incr was called immediately');
|
||||
setTimeout(debouncedIncr, 30);
|
||||
setTimeout(debouncedIncr, 60);
|
||||
@@ -163,7 +196,7 @@ $(document).ready(function() {
|
||||
_.delay(function(){ equal(counter, 1, "incr was debounced"); start(); }, 220);
|
||||
});
|
||||
|
||||
asyncTest("functions: debounce asap recursively", 2, function() {
|
||||
asyncTest("debounce asap recursively", 2, function() {
|
||||
var counter = 0;
|
||||
var debouncedIncr = _.debounce(function(){
|
||||
counter++;
|
||||
@@ -174,7 +207,7 @@ $(document).ready(function() {
|
||||
_.delay(function(){ equal(counter, 1, "incr was debounced"); start(); }, 70);
|
||||
});
|
||||
|
||||
test("functions: once", function() {
|
||||
test("once", function() {
|
||||
var num = 0;
|
||||
var increment = _.once(function(){ num++; });
|
||||
increment();
|
||||
@@ -182,7 +215,7 @@ $(document).ready(function() {
|
||||
equal(num, 1);
|
||||
});
|
||||
|
||||
test("functions: wrap", function() {
|
||||
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 saluation function');
|
||||
@@ -198,7 +231,7 @@ $(document).ready(function() {
|
||||
deepEqual(ret, [noop, ['whats', 'your'], 'vector', 'victor']);
|
||||
});
|
||||
|
||||
test("functions: compose", function() {
|
||||
test("compose", function() {
|
||||
var greet = function(name){ return "hi: " + name; };
|
||||
var exclaim = function(sentence){ return sentence + '!'; };
|
||||
var composed = _.compose(exclaim, greet);
|
||||
@@ -208,7 +241,7 @@ $(document).ready(function() {
|
||||
equal(composed('moe'), 'hi: moe!', 'in this case, the functions are also commutative');
|
||||
});
|
||||
|
||||
test("functions: after", function() {
|
||||
test("after", function() {
|
||||
var testAfter = function(afterAmount, timesCalled) {
|
||||
var afterCalled = 0;
|
||||
var after = _.after(afterAmount, function() {
|
||||
|
||||
148
vendor/underscore/test/objects.js
vendored
148
vendor/underscore/test/objects.js
vendored
@@ -2,7 +2,7 @@ $(document).ready(function() {
|
||||
|
||||
module("Objects");
|
||||
|
||||
test("objects: keys", function() {
|
||||
test("keys", function() {
|
||||
equal(_.keys({one : 1, two : 2}).join(', '), 'one, two', 'can extract the keys from an object');
|
||||
// the test above is not safe because it relies on for-in enumeration order
|
||||
var a = []; a[1] = 0;
|
||||
@@ -14,11 +14,26 @@ $(document).ready(function() {
|
||||
raises(function() { _.keys(true); }, TypeError, 'throws an error for boolean primitives');
|
||||
});
|
||||
|
||||
test("objects: values", function() {
|
||||
equal(_.values({one : 1, two : 2}).join(', '), '1, 2', 'can extract the values from an object');
|
||||
test("values", function() {
|
||||
equal(_.values({one: 1, two: 2}).join(', '), '1, 2', 'can extract the values from an object');
|
||||
equal(_.values({one: 1, two: 2, length: 3}).join(', '), '1, 2, 3', '... even when one of them is "length"');
|
||||
});
|
||||
|
||||
test("objects: functions", function() {
|
||||
test("pairs", function() {
|
||||
deepEqual(_.pairs({one: 1, two: 2}), [['one', 1], ['two', 2]], 'can convert an object into pairs');
|
||||
deepEqual(_.pairs({one: 1, two: 2, length: 3}), [['one', 1], ['two', 2], ['length', 3]], '... even when one of them is "length"');
|
||||
});
|
||||
|
||||
test("invert", function() {
|
||||
var obj = {first: 'Moe', second: 'Larry', third: 'Curly'};
|
||||
equal(_.keys(_.invert(obj)).join(' '), 'Moe Larry Curly', 'can invert an object');
|
||||
ok(_.isEqual(_.invert(_.invert(obj)), obj), 'two inverts gets you back where you started');
|
||||
|
||||
var obj = {length: 3};
|
||||
ok(_.invert(obj)['3'] == 'length', 'can invert an object with "length"')
|
||||
});
|
||||
|
||||
test("functions", function() {
|
||||
var obj = {a : 'dash', b : _.map, c : (/yo/), d : _.reduce};
|
||||
ok(_.isEqual(['b', 'd'], _.functions(obj)), 'can grab the function names of any passed-in object');
|
||||
|
||||
@@ -27,7 +42,7 @@ $(document).ready(function() {
|
||||
equal(_.functions(new Animal).join(''), 'run', 'also looks up functions on the prototype');
|
||||
});
|
||||
|
||||
test("objects: extend", function() {
|
||||
test("extend", function() {
|
||||
var result;
|
||||
equal(_.extend({}, {a:'b'}).a, 'b', 'can extend an object with the attributes of another');
|
||||
equal(_.extend({a:'x'}, {a:'b'}).a, 'b', 'properties in source override destination');
|
||||
@@ -40,7 +55,7 @@ $(document).ready(function() {
|
||||
equal(_.keys(result).join(''), 'ab', 'extend does not copy undefined values');
|
||||
});
|
||||
|
||||
test("objects: pick", function() {
|
||||
test("pick", function() {
|
||||
var result;
|
||||
result = _.pick({a:1, b:2, c:3}, 'a', 'c');
|
||||
ok(_.isEqual(result, {a:1, c:3}), 'can restrict properties to those named');
|
||||
@@ -54,7 +69,7 @@ $(document).ready(function() {
|
||||
ok(_.isEqual(_.pick(new Obj, 'a', 'c'), {a:1, c: 3}), 'include prototype props');
|
||||
});
|
||||
|
||||
test("objects: omit", function() {
|
||||
test("omit", function() {
|
||||
var result;
|
||||
result = _.omit({a:1, b:2, c:3}, 'b');
|
||||
ok(_.isEqual(result, {a:1, c:3}), 'can omit a single named property');
|
||||
@@ -68,7 +83,7 @@ $(document).ready(function() {
|
||||
ok(_.isEqual(_.omit(new Obj, 'b'), {a:1, c: 3}), 'include prototype props');
|
||||
});
|
||||
|
||||
test("objects: defaults", function() {
|
||||
test("defaults", function() {
|
||||
var result;
|
||||
var options = {zero: 0, one: 1, empty: "", nan: NaN, string: "string"};
|
||||
|
||||
@@ -83,7 +98,7 @@ $(document).ready(function() {
|
||||
equal(options.word, "word", 'new value is added, first one wins');
|
||||
});
|
||||
|
||||
test("objects: clone", function() {
|
||||
test("clone", function() {
|
||||
var moe = {name : 'moe', lucky : [13, 27, 34]};
|
||||
var clone = _.clone(moe);
|
||||
equal(clone.name, 'moe', 'the clone as the attributes of the original');
|
||||
@@ -99,7 +114,7 @@ $(document).ready(function() {
|
||||
equal(_.clone(null), null, 'non objects should not be changed by clone');
|
||||
});
|
||||
|
||||
test("objects: isEqual", function() {
|
||||
test("isEqual", function() {
|
||||
function First() {
|
||||
this.value = 1;
|
||||
}
|
||||
@@ -218,14 +233,6 @@ $(document).ready(function() {
|
||||
ok(_.isEqual(Array(3), Array(3)), "Sparse arrays of identical lengths are equal");
|
||||
ok(!_.isEqual(Array(3), Array(6)), "Sparse arrays of different lengths are not equal when both are empty");
|
||||
|
||||
// According to the Microsoft deviations spec, section 2.1.26, JScript 5.x treats `undefined`
|
||||
// elements in arrays as elisions. Thus, sparse arrays and dense arrays containing `undefined`
|
||||
// values are equivalent.
|
||||
if (0 in [undefined]) {
|
||||
ok(!_.isEqual(Array(3), [undefined, undefined, undefined]), "Sparse and dense arrays are not equal");
|
||||
ok(!_.isEqual([undefined, undefined, undefined], Array(3)), "Commutative equality is implemented for sparse and dense arrays");
|
||||
}
|
||||
|
||||
// Simple objects.
|
||||
ok(_.isEqual({a: "Curly", b: 1, c: true}, {a: "Curly", b: 1, c: true}), "Objects containing identical primitives are equal");
|
||||
ok(_.isEqual({a: /Curly/g, b: new Date(2009, 11, 13)}, {a: /Curly/g, b: new Date(2009, 11, 13)}), "Objects containing equivalent members are equal");
|
||||
@@ -283,6 +290,12 @@ $(document).ready(function() {
|
||||
b.push("Curly");
|
||||
ok(!_.isEqual(a, b), "Arrays containing circular references and different properties are not equal");
|
||||
|
||||
// More circular arrays #767.
|
||||
a = ["everything is checked but", "this", "is not"];
|
||||
a[1] = a;
|
||||
b = ["everything is checked but", ["this", "array"], "is not"];
|
||||
ok(!_.isEqual(a, b), "Comparison of circular references with non-circular references are not equal");
|
||||
|
||||
// Circular Objects.
|
||||
a = {abc: null};
|
||||
b = {abc: null};
|
||||
@@ -296,6 +309,12 @@ $(document).ready(function() {
|
||||
b.def = new Number(63);
|
||||
ok(!_.isEqual(a, b), "Objects containing circular references and different properties are not equal");
|
||||
|
||||
// More circular objects #767.
|
||||
a = {everything: "is checked", but: "this", is: "not"};
|
||||
a.but = a;
|
||||
b = {everything: "is checked", but: {that:"object"}, is: "not"};
|
||||
ok(!_.isEqual(a, b), "Comparison of circular references with non-circular object references are not equal");
|
||||
|
||||
// Cyclic Structures.
|
||||
a = [{abc: null}];
|
||||
b = [{abc: null}];
|
||||
@@ -329,60 +348,11 @@ $(document).ready(function() {
|
||||
ok(!_.isEqual(isEqualObj, {}), 'Objects that do not implement equivalent `isEqual` methods are not equal');
|
||||
ok(!_.isEqual({}, isEqualObj), 'Commutative equality is implemented for objects with different `isEqual` methods');
|
||||
|
||||
// Custom `isEqual` methods - comparing different types
|
||||
LocalizedString = (function() {
|
||||
function LocalizedString(id) { this.id = id; this.string = (this.id===10)? 'Bonjour': ''; }
|
||||
LocalizedString.prototype.isEqual = function(that) {
|
||||
if (_.isString(that)) return this.string == that;
|
||||
else if (that instanceof LocalizedString) return this.id == that.id;
|
||||
return false;
|
||||
};
|
||||
return LocalizedString;
|
||||
})();
|
||||
var localized_string1 = new LocalizedString(10), localized_string2 = new LocalizedString(10), localized_string3 = new LocalizedString(11);
|
||||
ok(_.isEqual(localized_string1, localized_string2), 'comparing same typed instances with same ids');
|
||||
ok(!_.isEqual(localized_string1, localized_string3), 'comparing same typed instances with different ids');
|
||||
ok(_.isEqual(localized_string1, 'Bonjour'), 'comparing different typed instances with same values');
|
||||
ok(_.isEqual('Bonjour', localized_string1), 'comparing different typed instances with same values');
|
||||
ok(!_.isEqual('Bonjour', localized_string3), 'comparing two localized strings with different ids');
|
||||
ok(!_.isEqual(localized_string1, 'Au revoir'), 'comparing different typed instances with different values');
|
||||
ok(!_.isEqual('Au revoir', localized_string1), 'comparing different typed instances with different values');
|
||||
|
||||
// Custom `isEqual` methods - comparing with serialized data
|
||||
Date.prototype.toJSON = function() {
|
||||
return {
|
||||
_type:'Date',
|
||||
year:this.getUTCFullYear(),
|
||||
month:this.getUTCMonth(),
|
||||
day:this.getUTCDate(),
|
||||
hours:this.getUTCHours(),
|
||||
minutes:this.getUTCMinutes(),
|
||||
seconds:this.getUTCSeconds()
|
||||
};
|
||||
};
|
||||
Date.prototype.isEqual = function(that) {
|
||||
var this_date_components = this.toJSON();
|
||||
var that_date_components = (that instanceof Date) ? that.toJSON() : that;
|
||||
delete this_date_components['_type']; delete that_date_components['_type'];
|
||||
return _.isEqual(this_date_components, that_date_components);
|
||||
};
|
||||
|
||||
var date = new Date();
|
||||
var date_json = {
|
||||
_type:'Date',
|
||||
year:date.getUTCFullYear(),
|
||||
month:date.getUTCMonth(),
|
||||
day:date.getUTCDate(),
|
||||
hours:date.getUTCHours(),
|
||||
minutes:date.getUTCMinutes(),
|
||||
seconds:date.getUTCSeconds()
|
||||
};
|
||||
|
||||
ok(_.isEqual(date_json, date), 'serialized date matches date');
|
||||
ok(_.isEqual(date, date_json), 'date matches serialized date');
|
||||
// Objects from another frame.
|
||||
ok(_.isEqual({}, iObject));
|
||||
});
|
||||
|
||||
test("objects: isEmpty", function() {
|
||||
test("isEmpty", function() {
|
||||
ok(!_([1]).isEmpty(), '[1] is not empty');
|
||||
ok(_.isEmpty([]), '[] is empty');
|
||||
ok(!_.isEmpty({one : 1}), '{one : 1} is not empty');
|
||||
@@ -416,17 +386,18 @@ $(document).ready(function() {
|
||||
parent.iNull = null;\
|
||||
parent.iBoolean = new Boolean(false);\
|
||||
parent.iUndefined = undefined;\
|
||||
parent.iObject = {};\
|
||||
</script>"
|
||||
);
|
||||
iDoc.close();
|
||||
|
||||
test("objects: isElement", function() {
|
||||
test("isElement", function() {
|
||||
ok(!_.isElement('div'), 'strings are not dom elements');
|
||||
ok(_.isElement($('html')[0]), 'the html tag is a DOM element');
|
||||
ok(_.isElement(iElement), 'even from another frame');
|
||||
});
|
||||
|
||||
test("objects: isArguments", function() {
|
||||
test("isArguments", function() {
|
||||
var args = (function(){ return arguments; })(1, 2, 3);
|
||||
ok(!_.isArguments('string'), 'a string is not an arguments object');
|
||||
ok(!_.isArguments(_.isArguments), 'a function is not an arguments object');
|
||||
@@ -436,7 +407,7 @@ $(document).ready(function() {
|
||||
ok(_.isArguments(iArguments), 'even from another frame');
|
||||
});
|
||||
|
||||
test("objects: isObject", function() {
|
||||
test("isObject", function() {
|
||||
ok(_.isObject(arguments), 'the arguments object is object');
|
||||
ok(_.isObject([1, 2, 3]), 'and arrays');
|
||||
ok(_.isObject($('html')[0]), 'and DOM element');
|
||||
@@ -451,19 +422,19 @@ $(document).ready(function() {
|
||||
ok(_.isObject(new String('string')), 'but new String()');
|
||||
});
|
||||
|
||||
test("objects: isArray", function() {
|
||||
test("isArray", function() {
|
||||
ok(!_.isArray(arguments), 'the arguments object is not an array');
|
||||
ok(_.isArray([1, 2, 3]), 'but arrays are');
|
||||
ok(_.isArray(iArray), 'even from another frame');
|
||||
});
|
||||
|
||||
test("objects: isString", function() {
|
||||
test("isString", function() {
|
||||
ok(!_.isString(document.body), 'the document body is not a string');
|
||||
ok(_.isString([1, 2, 3].join(', ')), 'but strings are');
|
||||
ok(_.isString(iString), 'even from another frame');
|
||||
});
|
||||
|
||||
test("objects: isNumber", function() {
|
||||
test("isNumber", function() {
|
||||
ok(!_.isNumber('string'), 'a string is not a number');
|
||||
ok(!_.isNumber(arguments), 'the arguments object is not a number');
|
||||
ok(!_.isNumber(undefined), 'undefined is not a number');
|
||||
@@ -474,7 +445,7 @@ $(document).ready(function() {
|
||||
ok(!_.isNumber('1'), 'numeric strings are not numbers');
|
||||
});
|
||||
|
||||
test("objects: isBoolean", function() {
|
||||
test("isBoolean", function() {
|
||||
ok(!_.isBoolean(2), 'a number is not a boolean');
|
||||
ok(!_.isBoolean("string"), 'a string is not a boolean');
|
||||
ok(!_.isBoolean("false"), 'the string "false" is not a boolean');
|
||||
@@ -488,33 +459,35 @@ $(document).ready(function() {
|
||||
ok(_.isBoolean(iBoolean), 'even from another frame');
|
||||
});
|
||||
|
||||
test("objects: isFunction", function() {
|
||||
test("isFunction", function() {
|
||||
ok(!_.isFunction([1, 2, 3]), 'arrays are not functions');
|
||||
ok(!_.isFunction('moe'), 'strings are not functions');
|
||||
ok(_.isFunction(_.isFunction), 'but functions are');
|
||||
ok(_.isFunction(iFunction), 'even from another frame');
|
||||
});
|
||||
|
||||
test("objects: isDate", function() {
|
||||
test("isDate", function() {
|
||||
ok(!_.isDate(100), 'numbers are not dates');
|
||||
ok(!_.isDate({}), 'objects are not dates');
|
||||
ok(_.isDate(new Date()), 'but dates are');
|
||||
ok(_.isDate(iDate), 'even from another frame');
|
||||
});
|
||||
|
||||
test("objects: isRegExp", function() {
|
||||
test("isRegExp", function() {
|
||||
ok(!_.isRegExp(_.identity), 'functions are not RegExps');
|
||||
ok(_.isRegExp(/identity/), 'but RegExps are');
|
||||
ok(_.isRegExp(iRegExp), 'even from another frame');
|
||||
});
|
||||
|
||||
test("objects: isFinite", function() {
|
||||
test("isFinite", function() {
|
||||
ok(!_.isFinite(undefined), 'undefined is not Finite');
|
||||
ok(!_.isFinite(null), 'null is not Finite');
|
||||
ok(!_.isFinite(NaN), 'NaN is not Finite');
|
||||
ok(!_.isFinite(Infinity), 'Infinity is not Finite');
|
||||
ok(!_.isFinite(-Infinity), '-Infinity is not Finite');
|
||||
ok(!_.isFinite('12'), 'Strings are not numbers');
|
||||
ok(_.isFinite('12'), 'Numeric strings are numbers');
|
||||
ok(!_.isFinite('1a'), 'Non numeric strings are not numbers');
|
||||
ok(!_.isFinite(''), 'Empty strings are not numbers');
|
||||
var obj = new Number(5);
|
||||
ok(_.isFinite(obj), 'Number instances can be finite');
|
||||
ok(_.isFinite(0), '0 is Finite');
|
||||
@@ -522,22 +495,23 @@ $(document).ready(function() {
|
||||
ok(_.isFinite(-12.44), 'Floats are Finite');
|
||||
});
|
||||
|
||||
test("objects: isNaN", function() {
|
||||
test("isNaN", function() {
|
||||
ok(!_.isNaN(undefined), 'undefined is not NaN');
|
||||
ok(!_.isNaN(null), 'null is not NaN');
|
||||
ok(!_.isNaN(0), '0 is not NaN');
|
||||
ok(_.isNaN(NaN), 'but NaN is');
|
||||
ok(_.isNaN(iNaN), 'even from another frame');
|
||||
ok(_.isNaN(new Number(NaN)), 'wrapped NaN is still NaN');
|
||||
});
|
||||
|
||||
test("objects: isNull", function() {
|
||||
test("isNull", function() {
|
||||
ok(!_.isNull(undefined), 'undefined is not null');
|
||||
ok(!_.isNull(NaN), 'NaN is not null');
|
||||
ok(_.isNull(null), 'but null is');
|
||||
ok(_.isNull(iNull), 'even from another frame');
|
||||
});
|
||||
|
||||
test("objects: isUndefined", function() {
|
||||
test("isUndefined", function() {
|
||||
ok(!_.isUndefined(1), 'numbers are defined');
|
||||
ok(!_.isUndefined(null), 'null is defined');
|
||||
ok(!_.isUndefined(false), 'false is defined');
|
||||
@@ -548,7 +522,7 @@ $(document).ready(function() {
|
||||
});
|
||||
|
||||
if (window.ActiveXObject) {
|
||||
test("objects: IE host objects", function() {
|
||||
test("IE host objects", function() {
|
||||
var xml = new ActiveXObject("Msxml2.DOMDocument.3.0");
|
||||
ok(!_.isNumber(xml));
|
||||
ok(!_.isBoolean(xml));
|
||||
@@ -559,7 +533,7 @@ $(document).ready(function() {
|
||||
});
|
||||
}
|
||||
|
||||
test("objects: tap", function() {
|
||||
test("tap", function() {
|
||||
var intercepted = null;
|
||||
var interceptor = function(obj) { intercepted = obj; };
|
||||
var returned = _.tap(1, interceptor);
|
||||
|
||||
46
vendor/underscore/test/utility.js
vendored
46
vendor/underscore/test/utility.js
vendored
@@ -14,18 +14,24 @@ $(document).ready(function() {
|
||||
|
||||
});
|
||||
|
||||
test("utility: identity", function() {
|
||||
test("#750 - Return _ instance.", 2, function() {
|
||||
var instance = _([]);
|
||||
ok(_(instance) === instance);
|
||||
ok(new _(instance) === instance);
|
||||
});
|
||||
|
||||
test("identity", function() {
|
||||
var moe = {name : 'moe'};
|
||||
equal(_.identity(moe), moe, 'moe is the same as his identity');
|
||||
});
|
||||
|
||||
test("utility: uniqueId", function() {
|
||||
test("uniqueId", function() {
|
||||
var ids = [], i = 0;
|
||||
while(i++ < 100) ids.push(_.uniqueId());
|
||||
equal(_.uniq(ids).length, ids.length, 'can generate a globally-unique stream of ids');
|
||||
});
|
||||
|
||||
test("utility: times", function() {
|
||||
test("times", function() {
|
||||
var vals = [];
|
||||
_.times(3, function (i) { vals.push(i); });
|
||||
ok(_.isEqual(vals, [0,1,2]), "is 0 indexed");
|
||||
@@ -35,7 +41,7 @@ $(document).ready(function() {
|
||||
ok(_.isEqual(vals, [0,1,2]), "works as a wrapper");
|
||||
});
|
||||
|
||||
test("utility: mixin", function() {
|
||||
test("mixin", function() {
|
||||
_.mixin({
|
||||
myReverse: function(string) {
|
||||
return string.split('').reverse().join('');
|
||||
@@ -45,12 +51,21 @@ $(document).ready(function() {
|
||||
equal(_('champ').myReverse(), 'pmahc', 'mixed in a function to the OOP wrapper');
|
||||
});
|
||||
|
||||
test("utility: _.escape", function() {
|
||||
test("_.escape", function() {
|
||||
equal(_.escape("Curly & Moe"), "Curly & Moe");
|
||||
equal(_.escape("Curly & Moe"), "Curly &amp; Moe");
|
||||
equal(_.escape(null), '');
|
||||
});
|
||||
|
||||
test("utility: template", function() {
|
||||
test("_.unescape", function() {
|
||||
var string = "Curly & Moe";
|
||||
equal(_.unescape("Curly & Moe"), string);
|
||||
equal(_.unescape("Curly &amp; Moe"), "Curly & Moe");
|
||||
equal(_.unescape(null), '');
|
||||
equal(_.unescape(_.escape(string)), string);
|
||||
});
|
||||
|
||||
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');
|
||||
@@ -156,6 +171,14 @@ $(document).ready(function() {
|
||||
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() {
|
||||
try {
|
||||
_.template('<b><%= if %></b>');
|
||||
} catch (e) {
|
||||
ok(e.source.indexOf('( if )') > 0);
|
||||
}
|
||||
});
|
||||
|
||||
test('_.template handles \\u2028 & \\u2029', function() {
|
||||
var tmpl = _.template('<p>\u2028<%= "\\u2028\\u2029" %>\u2029</p>');
|
||||
strictEqual(tmpl(), '<p>\u2028\u2028\u2029\u2029</p>');
|
||||
@@ -212,4 +235,15 @@ $(document).ready(function() {
|
||||
templateEscaped({f: function(){ ok(!(countEscaped++)); }});
|
||||
});
|
||||
|
||||
test('#746 - _.template settings are not modified.', 1, function() {
|
||||
var settings = {};
|
||||
_.template('', null, settings);
|
||||
deepEqual(settings, {});
|
||||
});
|
||||
|
||||
test('#779 - delimeters are applied to unescaped text.', 1, function() {
|
||||
var template = _.template('<<\nx\n>>', null, {evaluate: /<<(.*?)>>/g});
|
||||
strictEqual(template(), '<<\nx\n>>');
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
670
vendor/underscore/test/vendor/jslitmus.js
vendored
670
vendor/underscore/test/vendor/jslitmus.js
vendored
@@ -1,670 +0,0 @@
|
||||
// JSLitmus.js
|
||||
//
|
||||
// History:
|
||||
// 2008-10-27: Initial release
|
||||
// 2008-11-09: Account for iteration loop overhead
|
||||
// 2008-11-13: Added OS detection
|
||||
// 2009-02-25: Create tinyURL automatically, shift-click runs tests in reverse
|
||||
//
|
||||
// Copyright (c) 2008-2009, Robert Kieffer
|
||||
// All Rights Reserved
|
||||
//
|
||||
// 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 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.
|
||||
|
||||
(function() {
|
||||
// Private methods and state
|
||||
|
||||
// Get platform info but don't go crazy trying to recognize everything
|
||||
// that's out there. This is just for the major platforms and OSes.
|
||||
var platform = 'unknown platform', ua = navigator.userAgent;
|
||||
|
||||
// Detect OS
|
||||
var oses = ['Windows','iPhone OS','(Intel |PPC )?Mac OS X','Linux'].join('|');
|
||||
var pOS = new RegExp('((' + oses + ') [^ \);]*)').test(ua) ? RegExp.$1 : null;
|
||||
if (!pOS) pOS = new RegExp('((' + oses + ')[^ \);]*)').test(ua) ? RegExp.$1 : null;
|
||||
|
||||
// Detect browser
|
||||
var pName = /(Chrome|MSIE|Safari|Opera|Firefox)/.test(ua) ? RegExp.$1 : null;
|
||||
|
||||
// Detect version
|
||||
var vre = new RegExp('(Version|' + pName + ')[ \/]([^ ;]*)');
|
||||
var pVersion = (pName && vre.test(ua)) ? RegExp.$2 : null;
|
||||
var platform = (pOS && pName && pVersion) ? pName + ' ' + pVersion + ' on ' + pOS : 'unknown platform';
|
||||
|
||||
/**
|
||||
* A smattering of methods that are needed to implement the JSLitmus testbed.
|
||||
*/
|
||||
var jsl = {
|
||||
/**
|
||||
* Enhanced version of escape()
|
||||
*/
|
||||
escape: function(s) {
|
||||
s = s.replace(/,/g, '\\,');
|
||||
s = escape(s);
|
||||
s = s.replace(/\+/g, '%2b');
|
||||
s = s.replace(/ /g, '+');
|
||||
return s;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get an element by ID.
|
||||
*/
|
||||
$: function(id) {
|
||||
return document.getElementById(id);
|
||||
},
|
||||
|
||||
/**
|
||||
* Null function
|
||||
*/
|
||||
F: function() {},
|
||||
|
||||
/**
|
||||
* Set the status shown in the UI
|
||||
*/
|
||||
status: function(msg) {
|
||||
var el = jsl.$('jsl_status');
|
||||
if (el) el.innerHTML = msg || '';
|
||||
},
|
||||
|
||||
/**
|
||||
* Convert a number to an abbreviated string like, "15K" or "10M"
|
||||
*/
|
||||
toLabel: function(n) {
|
||||
if (n == Infinity) {
|
||||
return 'Infinity';
|
||||
} else if (n > 1e9) {
|
||||
n = Math.round(n/1e8);
|
||||
return n/10 + 'B';
|
||||
} else if (n > 1e6) {
|
||||
n = Math.round(n/1e5);
|
||||
return n/10 + 'M';
|
||||
} else if (n > 1e3) {
|
||||
n = Math.round(n/1e2);
|
||||
return n/10 + 'K';
|
||||
}
|
||||
return n;
|
||||
},
|
||||
|
||||
/**
|
||||
* Copy properties from src to dst
|
||||
*/
|
||||
extend: function(dst, src) {
|
||||
for (var k in src) dst[k] = src[k]; return dst;
|
||||
},
|
||||
|
||||
/**
|
||||
* Like Array.join(), but for the key-value pairs in an object
|
||||
*/
|
||||
join: function(o, delimit1, delimit2) {
|
||||
if (o.join) return o.join(delimit1); // If it's an array
|
||||
var pairs = [];
|
||||
for (var k in o) pairs.push(k + delimit1 + o[k]);
|
||||
return pairs.join(delimit2);
|
||||
},
|
||||
|
||||
/**
|
||||
* Array#indexOf isn't supported in IE, so we use this as a cross-browser solution
|
||||
*/
|
||||
indexOf: function(arr, o) {
|
||||
if (arr.indexOf) return arr.indexOf(o);
|
||||
for (var i = 0; i < this.length; i++) if (arr[i] === o) return i;
|
||||
return -1;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Test manages a single test (created with
|
||||
* JSLitmus.test())
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
var Test = function (name, f) {
|
||||
if (!f) throw new Error('Undefined test function');
|
||||
if (!(/function[^\(]*\(([^,\)]*)/).test(f.toString())) {
|
||||
throw new Error('"' + name + '" test: Test is not a valid Function object');
|
||||
}
|
||||
this.loopArg = RegExp.$1;
|
||||
this.name = name;
|
||||
this.f = f;
|
||||
};
|
||||
|
||||
jsl.extend(Test, /** @lends Test */ {
|
||||
/** Calibration tests for establishing iteration loop overhead */
|
||||
CALIBRATIONS: [
|
||||
new Test('calibrating loop', function(count) {while (count--);}),
|
||||
new Test('calibrating function', jsl.F)
|
||||
],
|
||||
|
||||
/**
|
||||
* Run calibration tests. Returns true if calibrations are not yet
|
||||
* complete (in which case calling code should run the tests yet again).
|
||||
* onCalibrated - Callback to invoke when calibrations have finished
|
||||
*/
|
||||
calibrate: function(onCalibrated) {
|
||||
for (var i = 0; i < Test.CALIBRATIONS.length; i++) {
|
||||
var cal = Test.CALIBRATIONS[i];
|
||||
if (cal.running) return true;
|
||||
if (!cal.count) {
|
||||
cal.isCalibration = true;
|
||||
cal.onStop = onCalibrated;
|
||||
//cal.MIN_TIME = .1; // Do calibrations quickly
|
||||
cal.run(2e4);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
jsl.extend(Test.prototype, {/** @lends Test.prototype */
|
||||
/** Initial number of iterations */
|
||||
INIT_COUNT: 10,
|
||||
/** Max iterations allowed (i.e. used to detect bad looping functions) */
|
||||
MAX_COUNT: 1e9,
|
||||
/** Minimum time a test should take to get valid results (secs) */
|
||||
MIN_TIME: .5,
|
||||
|
||||
/** Callback invoked when test state changes */
|
||||
onChange: jsl.F,
|
||||
|
||||
/** Callback invoked when test is finished */
|
||||
onStop: jsl.F,
|
||||
|
||||
/**
|
||||
* Reset test state
|
||||
*/
|
||||
reset: function() {
|
||||
delete this.count;
|
||||
delete this.time;
|
||||
delete this.running;
|
||||
delete this.error;
|
||||
},
|
||||
|
||||
/**
|
||||
* Run the test (in a timeout). We use a timeout to make sure the browser
|
||||
* has a chance to finish rendering any UI changes we've made, like
|
||||
* updating the status message.
|
||||
*/
|
||||
run: function(count) {
|
||||
count = count || this.INIT_COUNT;
|
||||
jsl.status(this.name + ' x ' + count);
|
||||
this.running = true;
|
||||
var me = this;
|
||||
setTimeout(function() {me._run(count);}, 200);
|
||||
},
|
||||
|
||||
/**
|
||||
* The nuts and bolts code that actually runs a test
|
||||
*/
|
||||
_run: function(count) {
|
||||
var me = this;
|
||||
|
||||
// Make sure calibration tests have run
|
||||
if (!me.isCalibration && Test.calibrate(function() {me.run(count);})) return;
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
var start, f = this.f, now, i = count;
|
||||
|
||||
// Start the timer
|
||||
start = new Date();
|
||||
|
||||
// Now for the money shot. If this is a looping function ...
|
||||
if (this.loopArg) {
|
||||
// ... let it do the iteration itself
|
||||
f(count);
|
||||
} else {
|
||||
// ... otherwise do the iteration for it
|
||||
while (i--) f();
|
||||
}
|
||||
|
||||
// Get time test took (in secs)
|
||||
this.time = Math.max(1,new Date() - start)/1000;
|
||||
|
||||
// Store iteration count and per-operation time taken
|
||||
this.count = count;
|
||||
this.period = this.time/count;
|
||||
|
||||
// Do we need to do another run?
|
||||
this.running = this.time <= this.MIN_TIME;
|
||||
|
||||
// ... if so, compute how many times we should iterate
|
||||
if (this.running) {
|
||||
// Bump the count to the nearest power of 2
|
||||
var x = this.MIN_TIME/this.time;
|
||||
var pow = Math.pow(2, Math.max(1, Math.ceil(Math.log(x)/Math.log(2))));
|
||||
count *= pow;
|
||||
if (count > this.MAX_COUNT) {
|
||||
throw new Error('Max count exceeded. If this test uses a looping function, make sure the iteration loop is working properly.');
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// Exceptions are caught and displayed in the test UI
|
||||
this.reset();
|
||||
this.error = e;
|
||||
}
|
||||
|
||||
// Figure out what to do next
|
||||
if (this.running) {
|
||||
me.run(count);
|
||||
} else {
|
||||
jsl.status('');
|
||||
me.onStop(me);
|
||||
}
|
||||
|
||||
// Finish up
|
||||
this.onChange(this);
|
||||
},
|
||||
|
||||
/**
|
||||
* Get the number of operations per second for this test.
|
||||
*
|
||||
* @param normalize if true, iteration loop overhead taken into account
|
||||
*/
|
||||
getHz: function(/**Boolean*/ normalize) {
|
||||
var p = this.period;
|
||||
|
||||
// Adjust period based on the calibration test time
|
||||
if (normalize && !this.isCalibration) {
|
||||
var cal = Test.CALIBRATIONS[this.loopArg ? 0 : 1];
|
||||
|
||||
// If the period is within 20% of the calibration time, then zero the
|
||||
// it out
|
||||
p = p < cal.period*1.2 ? 0 : p - cal.period;
|
||||
}
|
||||
|
||||
return Math.round(1/p);
|
||||
},
|
||||
|
||||
/**
|
||||
* Get a friendly string describing the test
|
||||
*/
|
||||
toString: function() {
|
||||
return this.name + ' - ' + this.time/this.count + ' secs';
|
||||
}
|
||||
});
|
||||
|
||||
// CSS we need for the UI
|
||||
var STYLESHEET = '<style> \
|
||||
#jslitmus {font-family:sans-serif; font-size: 12px;} \
|
||||
#jslitmus a {text-decoration: none;} \
|
||||
#jslitmus a:hover {text-decoration: underline;} \
|
||||
#jsl_status { \
|
||||
margin-top: 10px; \
|
||||
font-size: 10px; \
|
||||
color: #888; \
|
||||
} \
|
||||
A IMG {border:none} \
|
||||
#test_results { \
|
||||
margin-top: 10px; \
|
||||
font-size: 12px; \
|
||||
font-family: sans-serif; \
|
||||
border-collapse: collapse; \
|
||||
border-spacing: 0px; \
|
||||
} \
|
||||
#test_results th, #test_results td { \
|
||||
border: solid 1px #ccc; \
|
||||
vertical-align: top; \
|
||||
padding: 3px; \
|
||||
} \
|
||||
#test_results th { \
|
||||
vertical-align: bottom; \
|
||||
background-color: #ccc; \
|
||||
padding: 1px; \
|
||||
font-size: 10px; \
|
||||
} \
|
||||
#test_results #test_platform { \
|
||||
color: #444; \
|
||||
text-align:center; \
|
||||
} \
|
||||
#test_results .test_row { \
|
||||
color: #006; \
|
||||
cursor: pointer; \
|
||||
} \
|
||||
#test_results .test_nonlooping { \
|
||||
border-left-style: dotted; \
|
||||
border-left-width: 2px; \
|
||||
} \
|
||||
#test_results .test_looping { \
|
||||
border-left-style: solid; \
|
||||
border-left-width: 2px; \
|
||||
} \
|
||||
#test_results .test_name {white-space: nowrap;} \
|
||||
#test_results .test_pending { \
|
||||
} \
|
||||
#test_results .test_running { \
|
||||
font-style: italic; \
|
||||
} \
|
||||
#test_results .test_done {} \
|
||||
#test_results .test_done { \
|
||||
text-align: right; \
|
||||
font-family: monospace; \
|
||||
} \
|
||||
#test_results .test_error {color: #600;} \
|
||||
#test_results .test_error .error_head {font-weight:bold;} \
|
||||
#test_results .test_error .error_body {font-size:85%;} \
|
||||
#test_results .test_row:hover td { \
|
||||
background-color: #ffc; \
|
||||
text-decoration: underline; \
|
||||
} \
|
||||
#chart { \
|
||||
margin: 10px 0px; \
|
||||
width: 250px; \
|
||||
} \
|
||||
#chart img { \
|
||||
border: solid 1px #ccc; \
|
||||
margin-bottom: 5px; \
|
||||
} \
|
||||
#chart #tiny_url { \
|
||||
height: 40px; \
|
||||
width: 250px; \
|
||||
} \
|
||||
#jslitmus_credit { \
|
||||
font-size: 10px; \
|
||||
color: #888; \
|
||||
margin-top: 8px; \
|
||||
} \
|
||||
</style>';
|
||||
|
||||
// HTML markup for the UI
|
||||
var MARKUP = '<div id="jslitmus"> \
|
||||
<button onclick="JSLitmus.runAll(event)">Run Tests</button> \
|
||||
<button id="stop_button" disabled="disabled" onclick="JSLitmus.stop()">Stop Tests</button> \
|
||||
<br \> \
|
||||
<br \> \
|
||||
<input type="checkbox" style="vertical-align: middle" id="test_normalize" checked="checked" onchange="JSLitmus.renderAll()""> Normalize results \
|
||||
<table id="test_results"> \
|
||||
<colgroup> \
|
||||
<col /> \
|
||||
<col width="100" /> \
|
||||
</colgroup> \
|
||||
<tr><th id="test_platform" colspan="2">' + platform + '</th></tr> \
|
||||
<tr><th>Test</th><th>Ops/sec</th></tr> \
|
||||
<tr id="test_row_template" class="test_row" style="display:none"> \
|
||||
<td class="test_name"></td> \
|
||||
<td class="test_result">Ready</td> \
|
||||
</tr> \
|
||||
</table> \
|
||||
<div id="jsl_status"></div> \
|
||||
<div id="chart" style="display:none"> \
|
||||
<a id="chart_link" target="_blank"><img id="chart_image"></a> \
|
||||
TinyURL (for chart): \
|
||||
<iframe id="tiny_url" frameBorder="0" scrolling="no" src=""></iframe> \
|
||||
</div> \
|
||||
<a id="jslitmus_credit" title="JSLitmus home page" href="http://code.google.com/p/jslitmus" target="_blank">Powered by JSLitmus</a> \
|
||||
</div>';
|
||||
|
||||
/**
|
||||
* The public API for creating and running tests
|
||||
*/
|
||||
window.JSLitmus = {
|
||||
/** The list of all tests that have been registered with JSLitmus.test */
|
||||
_tests: [],
|
||||
/** The queue of tests that need to be run */
|
||||
_queue: [],
|
||||
|
||||
/**
|
||||
* The parsed query parameters the current page URL. This is provided as a
|
||||
* convenience for test functions - it's not used by JSLitmus proper
|
||||
*/
|
||||
params: {},
|
||||
|
||||
/**
|
||||
* Initialize
|
||||
*/
|
||||
_init: function() {
|
||||
// Parse query params into JSLitmus.params[] hash
|
||||
var match = (location + '').match(/([^?#]*)(#.*)?$/);
|
||||
if (match) {
|
||||
var pairs = match[1].split('&');
|
||||
for (var i = 0; i < pairs.length; i++) {
|
||||
var pair = pairs[i].split('=');
|
||||
if (pair.length > 1) {
|
||||
var key = pair.shift();
|
||||
var value = pair.length > 1 ? pair.join('=') : pair[0];
|
||||
this.params[key] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Write out the stylesheet. We have to do this here because IE
|
||||
// doesn't honor sheets written after the document has loaded.
|
||||
document.write(STYLESHEET);
|
||||
|
||||
// Setup the rest of the UI once the document is loaded
|
||||
if (window.addEventListener) {
|
||||
window.addEventListener('load', this._setup, false);
|
||||
} else if (document.addEventListener) {
|
||||
document.addEventListener('load', this._setup, false);
|
||||
} else if (window.attachEvent) {
|
||||
window.attachEvent('onload', this._setup);
|
||||
}
|
||||
|
||||
return this;
|
||||
},
|
||||
|
||||
/**
|
||||
* Set up the UI
|
||||
*/
|
||||
_setup: function() {
|
||||
var el = jsl.$('jslitmus_container');
|
||||
if (!el) document.body.appendChild(el = document.createElement('div'));
|
||||
|
||||
el.innerHTML = MARKUP;
|
||||
|
||||
// Render the UI for all our tests
|
||||
for (var i=0; i < JSLitmus._tests.length; i++)
|
||||
JSLitmus.renderTest(JSLitmus._tests[i]);
|
||||
},
|
||||
|
||||
/**
|
||||
* (Re)render all the test results
|
||||
*/
|
||||
renderAll: function() {
|
||||
for (var i = 0; i < JSLitmus._tests.length; i++)
|
||||
JSLitmus.renderTest(JSLitmus._tests[i]);
|
||||
JSLitmus.renderChart();
|
||||
},
|
||||
|
||||
/**
|
||||
* (Re)render the chart graphics
|
||||
*/
|
||||
renderChart: function() {
|
||||
var url = JSLitmus.chartUrl();
|
||||
jsl.$('chart_link').href = url;
|
||||
jsl.$('chart_image').src = url;
|
||||
jsl.$('chart').style.display = '';
|
||||
|
||||
// Update the tiny URL
|
||||
jsl.$('tiny_url').src = 'http://tinyurl.com/api-create.php?url='+escape(url);
|
||||
},
|
||||
|
||||
/**
|
||||
* (Re)render the results for a specific test
|
||||
*/
|
||||
renderTest: function(test) {
|
||||
// Make a new row if needed
|
||||
if (!test._row) {
|
||||
var trow = jsl.$('test_row_template');
|
||||
if (!trow) return;
|
||||
|
||||
test._row = trow.cloneNode(true);
|
||||
test._row.style.display = '';
|
||||
test._row.id = '';
|
||||
test._row.onclick = function() {JSLitmus._queueTest(test);};
|
||||
test._row.title = 'Run ' + test.name + ' test';
|
||||
trow.parentNode.appendChild(test._row);
|
||||
test._row.cells[0].innerHTML = test.name;
|
||||
}
|
||||
|
||||
var cell = test._row.cells[1];
|
||||
var cns = [test.loopArg ? 'test_looping' : 'test_nonlooping'];
|
||||
|
||||
if (test.error) {
|
||||
cns.push('test_error');
|
||||
cell.innerHTML =
|
||||
'<div class="error_head">' + test.error + '</div>' +
|
||||
'<ul class="error_body"><li>' +
|
||||
jsl.join(test.error, ': ', '</li><li>') +
|
||||
'</li></ul>';
|
||||
} else {
|
||||
if (test.running) {
|
||||
cns.push('test_running');
|
||||
cell.innerHTML = 'running';
|
||||
} else if (jsl.indexOf(JSLitmus._queue, test) >= 0) {
|
||||
cns.push('test_pending');
|
||||
cell.innerHTML = 'pending';
|
||||
} else if (test.count) {
|
||||
cns.push('test_done');
|
||||
var hz = test.getHz(jsl.$('test_normalize').checked);
|
||||
cell.innerHTML = hz != Infinity ? hz : '∞';
|
||||
} else {
|
||||
cell.innerHTML = 'ready';
|
||||
}
|
||||
}
|
||||
cell.className = cns.join(' ');
|
||||
},
|
||||
|
||||
/**
|
||||
* Create a new test
|
||||
*/
|
||||
test: function(name, f) {
|
||||
// Create the Test object
|
||||
var test = new Test(name, f);
|
||||
JSLitmus._tests.push(test);
|
||||
|
||||
// Re-render if the test state changes
|
||||
test.onChange = JSLitmus.renderTest;
|
||||
|
||||
// Run the next test if this one finished
|
||||
test.onStop = function(test) {
|
||||
if (JSLitmus.onTestFinish) JSLitmus.onTestFinish(test);
|
||||
JSLitmus.currentTest = null;
|
||||
JSLitmus._nextTest();
|
||||
};
|
||||
|
||||
// Render the new test
|
||||
this.renderTest(test);
|
||||
},
|
||||
|
||||
/**
|
||||
* Add all tests to the run queue
|
||||
*/
|
||||
runAll: function(e) {
|
||||
e = e || window.event;
|
||||
var reverse = e && e.shiftKey, len = JSLitmus._tests.length;
|
||||
for (var i = 0; i < len; i++) {
|
||||
JSLitmus._queueTest(JSLitmus._tests[!reverse ? i : (len - i - 1)]);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Remove all tests from the run queue. The current test has to finish on
|
||||
* it's own though
|
||||
*/
|
||||
stop: function() {
|
||||
while (JSLitmus._queue.length) {
|
||||
var test = JSLitmus._queue.shift();
|
||||
JSLitmus.renderTest(test);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Run the next test in the run queue
|
||||
*/
|
||||
_nextTest: function() {
|
||||
if (!JSLitmus.currentTest) {
|
||||
var test = JSLitmus._queue.shift();
|
||||
if (test) {
|
||||
jsl.$('stop_button').disabled = false;
|
||||
JSLitmus.currentTest = test;
|
||||
test.run();
|
||||
JSLitmus.renderTest(test);
|
||||
if (JSLitmus.onTestStart) JSLitmus.onTestStart(test);
|
||||
} else {
|
||||
jsl.$('stop_button').disabled = true;
|
||||
JSLitmus.renderChart();
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Add a test to the run queue
|
||||
*/
|
||||
_queueTest: function(test) {
|
||||
if (jsl.indexOf(JSLitmus._queue, test) >= 0) return;
|
||||
JSLitmus._queue.push(test);
|
||||
JSLitmus.renderTest(test);
|
||||
JSLitmus._nextTest();
|
||||
},
|
||||
|
||||
/**
|
||||
* Generate a Google Chart URL that shows the data for all tests
|
||||
*/
|
||||
chartUrl: function() {
|
||||
var n = JSLitmus._tests.length, markers = [], data = [];
|
||||
var d, min = 0, max = -1e10;
|
||||
var normalize = jsl.$('test_normalize').checked;
|
||||
|
||||
// Gather test data
|
||||
for (var i=0; i < JSLitmus._tests.length; i++) {
|
||||
var test = JSLitmus._tests[i];
|
||||
if (test.count) {
|
||||
var hz = test.getHz(normalize);
|
||||
var v = hz != Infinity ? hz : 0;
|
||||
data.push(v);
|
||||
markers.push('t' + jsl.escape(test.name + '(' + jsl.toLabel(hz)+ ')') + ',000000,0,' +
|
||||
markers.length + ',10');
|
||||
max = Math.max(v, max);
|
||||
}
|
||||
}
|
||||
if (markers.length <= 0) return null;
|
||||
|
||||
// Build chart title
|
||||
var title = document.getElementsByTagName('title');
|
||||
title = (title && title.length) ? title[0].innerHTML : null;
|
||||
var chart_title = [];
|
||||
if (title) chart_title.push(title);
|
||||
chart_title.push('Ops/sec (' + platform + ')');
|
||||
|
||||
// Build labels
|
||||
var labels = [jsl.toLabel(min), jsl.toLabel(max)];
|
||||
|
||||
var w = 250, bw = 15;
|
||||
var bs = 5;
|
||||
var h = markers.length*(bw + bs) + 30 + chart_title.length*20;
|
||||
|
||||
var params = {
|
||||
chtt: escape(chart_title.join('|')),
|
||||
chts: '000000,10',
|
||||
cht: 'bhg', // chart type
|
||||
chd: 't:' + data.join(','), // data set
|
||||
chds: min + ',' + max, // max/min of data
|
||||
chxt: 'x', // label axes
|
||||
chxl: '0:|' + labels.join('|'), // labels
|
||||
chsp: '0,1',
|
||||
chm: markers.join('|'), // test names
|
||||
chbh: [bw, 0, bs].join(','), // bar widths
|
||||
// chf: 'bg,lg,0,eeeeee,0,eeeeee,.5,ffffff,1', // gradient
|
||||
chs: w + 'x' + h
|
||||
};
|
||||
return 'http://chart.apis.google.com/chart?' + jsl.join(params, '=', '&');
|
||||
}
|
||||
};
|
||||
|
||||
JSLitmus._init();
|
||||
})();
|
||||
236
vendor/underscore/test/vendor/qunit.css
vendored
236
vendor/underscore/test/vendor/qunit.css
vendored
@@ -1,236 +0,0 @@
|
||||
/**
|
||||
* QUnit v1.8.0 - A JavaScript Unit Testing Framework
|
||||
*
|
||||
* http://docs.jquery.com/QUnit
|
||||
*
|
||||
* Copyright (c) 2012 John Resig, Jörn Zaefferer
|
||||
* Dual licensed under the MIT (MIT-LICENSE.txt)
|
||||
* or GPL (GPL-LICENSE.txt) licenses.
|
||||
*/
|
||||
|
||||
/** 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-tests ol, #qunit-header, #qunit-banner, #qunit-userAgent, #qunit-testresult {
|
||||
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: 15px 15px 0 0;
|
||||
-moz-border-radius: 15px 15px 0 0;
|
||||
-webkit-border-top-right-radius: 15px;
|
||||
-webkit-border-top-left-radius: 15px;
|
||||
}
|
||||
|
||||
#qunit-header a {
|
||||
text-decoration: none;
|
||||
color: #c2ccd1;
|
||||
}
|
||||
|
||||
#qunit-header a:hover,
|
||||
#qunit-header a:focus {
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
#qunit-header label {
|
||||
display: inline-block;
|
||||
padding-left: 0.5em;
|
||||
}
|
||||
|
||||
#qunit-banner {
|
||||
height: 5px;
|
||||
}
|
||||
|
||||
#qunit-testrunner-toolbar {
|
||||
padding: 0.5em 0 0.5em 2em;
|
||||
color: #5E740B;
|
||||
background-color: #eee;
|
||||
}
|
||||
|
||||
#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;
|
||||
}
|
||||
|
||||
|
||||
/** 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 ol {
|
||||
margin-top: 0.5em;
|
||||
padding: 0.5em;
|
||||
|
||||
background-color: #fff;
|
||||
|
||||
border-radius: 15px;
|
||||
-moz-border-radius: 15px;
|
||||
-webkit-border-radius: 15px;
|
||||
|
||||
box-shadow: inset 0px 2px 13px #999;
|
||||
-moz-box-shadow: inset 0px 2px 13px #999;
|
||||
-webkit-box-shadow: inset 0px 2px 13px #999;
|
||||
}
|
||||
|
||||
#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 {
|
||||
margin: 0.5em;
|
||||
padding: 0.4em 0.5em 0.4em 0.5em;
|
||||
background-color: #fff;
|
||||
border-bottom: none;
|
||||
list-style-position: inside;
|
||||
}
|
||||
|
||||
/*** Passing Styles */
|
||||
|
||||
#qunit-tests li li.pass {
|
||||
color: #5E740B;
|
||||
background-color: #fff;
|
||||
border-left: 26px 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: 26px solid #EE5757;
|
||||
white-space: pre;
|
||||
}
|
||||
|
||||
#qunit-tests > li:last-child {
|
||||
border-radius: 0 0 15px 15px;
|
||||
-moz-border-radius: 0 0 15px 15px;
|
||||
-webkit-border-bottom-right-radius: 15px;
|
||||
-webkit-border-bottom-left-radius: 15px;
|
||||
}
|
||||
|
||||
#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;
|
||||
}
|
||||
1863
vendor/underscore/test/vendor/qunit.js
vendored
1863
vendor/underscore/test/vendor/qunit.js
vendored
File diff suppressed because it is too large
Load Diff
37
vendor/underscore/underscore-min.js
vendored
37
vendor/underscore/underscore-min.js
vendored
File diff suppressed because one or more lines are too long
503
vendor/underscore/underscore.js
vendored
503
vendor/underscore/underscore.js
vendored
@@ -1,10 +1,7 @@
|
||||
// Underscore.js 1.3.3
|
||||
// Underscore.js 1.4.2
|
||||
// http://underscorejs.org
|
||||
// (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
|
||||
// Underscore may be freely distributed under the MIT license.
|
||||
// Portions of Underscore are inspired or borrowed from Prototype,
|
||||
// Oliver Steele's Functional, and John Resig's Micro-Templating.
|
||||
// For all details and documentation:
|
||||
// http://documentcloud.github.com/underscore
|
||||
|
||||
(function() {
|
||||
|
||||
@@ -26,6 +23,7 @@
|
||||
// Create quick reference variables for speed access to core prototypes.
|
||||
var push = ArrayProto.push,
|
||||
slice = ArrayProto.slice,
|
||||
concat = ArrayProto.concat,
|
||||
unshift = ArrayProto.unshift,
|
||||
toString = ObjProto.toString,
|
||||
hasOwnProperty = ObjProto.hasOwnProperty;
|
||||
@@ -47,7 +45,11 @@
|
||||
nativeBind = FuncProto.bind;
|
||||
|
||||
// Create a safe reference to the Underscore object for use below.
|
||||
var _ = function(obj) { return new wrapper(obj); };
|
||||
var _ = function(obj) {
|
||||
if (obj instanceof _) return obj;
|
||||
if (!(this instanceof _)) return new _(obj);
|
||||
this._wrapped = obj;
|
||||
};
|
||||
|
||||
// Export the Underscore object for **Node.js**, with
|
||||
// backwards-compatibility for the old `require()` API. If we're in
|
||||
@@ -63,7 +65,7 @@
|
||||
}
|
||||
|
||||
// Current version.
|
||||
_.VERSION = '1.3.3';
|
||||
_.VERSION = '1.4.2';
|
||||
|
||||
// Collection Functions
|
||||
// --------------------
|
||||
@@ -128,11 +130,24 @@
|
||||
if (obj == null) obj = [];
|
||||
if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
|
||||
if (context) iterator = _.bind(iterator, context);
|
||||
return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
|
||||
return arguments.length > 2 ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
|
||||
}
|
||||
var reversed = _.toArray(obj).reverse();
|
||||
if (context && !initial) iterator = _.bind(iterator, context);
|
||||
return initial ? _.reduce(reversed, iterator, memo, context) : _.reduce(reversed, iterator);
|
||||
var length = obj.length;
|
||||
if (length !== +length) {
|
||||
var keys = _.keys(obj);
|
||||
length = keys.length;
|
||||
}
|
||||
each(obj, function(value, index, list) {
|
||||
index = keys ? keys[--length] : --length;
|
||||
if (!initial) {
|
||||
memo = obj[index];
|
||||
initial = true;
|
||||
} else {
|
||||
memo = iterator.call(context, memo, obj[index], index, list);
|
||||
}
|
||||
});
|
||||
if (!initial) throw new TypeError('Reduce of empty array with no initial value');
|
||||
return memo;
|
||||
};
|
||||
|
||||
// Return the first value which passes a truth test. Aliased as `detect`.
|
||||
@@ -162,18 +177,16 @@
|
||||
|
||||
// Return all the elements for which a truth test fails.
|
||||
_.reject = function(obj, iterator, context) {
|
||||
var results = [];
|
||||
if (obj == null) return results;
|
||||
each(obj, function(value, index, list) {
|
||||
if (!iterator.call(context, value, index, list)) results[results.length] = value;
|
||||
});
|
||||
return results;
|
||||
return _.filter(obj, function(value, index, list) {
|
||||
return !iterator.call(context, value, index, list);
|
||||
}, context);
|
||||
};
|
||||
|
||||
// Determine whether all of the elements match a truth test.
|
||||
// Delegates to **ECMAScript 5**'s native `every` if available.
|
||||
// Aliased as `all`.
|
||||
_.every = _.all = function(obj, iterator, context) {
|
||||
iterator || (iterator = _.identity);
|
||||
var result = true;
|
||||
if (obj == null) return result;
|
||||
if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
|
||||
@@ -197,9 +210,9 @@
|
||||
return !!result;
|
||||
};
|
||||
|
||||
// Determine if a given value is included in the array or object using `===`.
|
||||
// Aliased as `contains`.
|
||||
_.include = _.contains = function(obj, target) {
|
||||
// Determine if the array or object contains a given value (using `===`).
|
||||
// Aliased as `include`.
|
||||
_.contains = _.include = function(obj, target) {
|
||||
var found = false;
|
||||
if (obj == null) return found;
|
||||
if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
|
||||
@@ -222,6 +235,18 @@
|
||||
return _.map(obj, function(value){ return value[key]; });
|
||||
};
|
||||
|
||||
// Convenience version of a common use case of `filter`: selecting only objects
|
||||
// with specific `key:value` pairs.
|
||||
_.where = function(obj, attrs) {
|
||||
if (_.isEmpty(attrs)) return [];
|
||||
return _.filter(obj, function(value) {
|
||||
for (var key in attrs) {
|
||||
if (attrs[key] !== value[key]) return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
};
|
||||
|
||||
// Return the maximum element or (element-based computation).
|
||||
// Can't optimize arrays of integers longer than 65,535 elements.
|
||||
// See: https://bugs.webkit.org/show_bug.cgi?id=80797
|
||||
@@ -258,40 +283,44 @@
|
||||
var index = 0;
|
||||
var shuffled = [];
|
||||
each(obj, function(value) {
|
||||
rand = Math.floor(Math.random() * ++index);
|
||||
rand = _.random(index++);
|
||||
shuffled[index - 1] = shuffled[rand];
|
||||
shuffled[rand] = value;
|
||||
});
|
||||
return shuffled;
|
||||
};
|
||||
|
||||
// An internal function to generate lookup iterators.
|
||||
var lookupIterator = function(value) {
|
||||
return _.isFunction(value) ? value : function(obj){ return obj[value]; };
|
||||
};
|
||||
|
||||
// Sort the object's values by a criterion produced by an iterator.
|
||||
_.sortBy = function(obj, val, context) {
|
||||
var iterator = lookupIterator(obj, val);
|
||||
_.sortBy = function(obj, value, context) {
|
||||
var iterator = lookupIterator(value);
|
||||
return _.pluck(_.map(obj, function(value, index, list) {
|
||||
return {
|
||||
value : value,
|
||||
index : index,
|
||||
criteria : iterator.call(context, value, index, list)
|
||||
};
|
||||
}).sort(function(left, right) {
|
||||
var a = left.criteria, b = right.criteria;
|
||||
if (a === void 0) return 1;
|
||||
if (b === void 0) return -1;
|
||||
return a < b ? -1 : a > b ? 1 : 0;
|
||||
var a = left.criteria;
|
||||
var b = right.criteria;
|
||||
if (a !== b) {
|
||||
if (a > b || a === void 0) return 1;
|
||||
if (a < b || b === void 0) return -1;
|
||||
}
|
||||
return left.index < right.index ? -1 : 1;
|
||||
}), 'value');
|
||||
};
|
||||
|
||||
// An internal function to generate lookup iterators.
|
||||
var lookupIterator = function(obj, val) {
|
||||
return _.isFunction(val) ? val : function(obj) { return obj[val]; };
|
||||
};
|
||||
|
||||
// An internal function used for aggregate "group by" operations.
|
||||
var group = function(obj, val, behavior) {
|
||||
var group = function(obj, value, context, behavior) {
|
||||
var result = {};
|
||||
var iterator = lookupIterator(obj, val);
|
||||
var iterator = lookupIterator(value);
|
||||
each(obj, function(value, index) {
|
||||
var key = iterator(value, index);
|
||||
var key = iterator.call(context, value, index, obj);
|
||||
behavior(result, key, value);
|
||||
});
|
||||
return result;
|
||||
@@ -299,46 +328,46 @@
|
||||
|
||||
// Groups the object's values by a criterion. Pass either a string attribute
|
||||
// to group by, or a function that returns the criterion.
|
||||
_.groupBy = function(obj, val) {
|
||||
return group(obj, val, function(result, key, value) {
|
||||
(result[key] || (result[key] = [])).push(value);
|
||||
_.groupBy = function(obj, value, context) {
|
||||
return group(obj, value, context, function(result, key, value) {
|
||||
(_.has(result, key) ? result[key] : (result[key] = [])).push(value);
|
||||
});
|
||||
};
|
||||
|
||||
// Counts instances of an object that group by a certain criterion. Pass
|
||||
// either a string attribute to count by, or a function that returns the
|
||||
// criterion.
|
||||
_.countBy = function(obj, val) {
|
||||
return group(obj, val, function(result, key, value) {
|
||||
result[key] || (result[key] = 0);
|
||||
_.countBy = function(obj, value, context) {
|
||||
return group(obj, value, context, function(result, key, value) {
|
||||
if (!_.has(result, key)) result[key] = 0;
|
||||
result[key]++;
|
||||
});
|
||||
};
|
||||
|
||||
// Use a comparator function to figure out the smallest index at which
|
||||
// an object should be inserted so as to maintain order. Uses binary search.
|
||||
_.sortedIndex = function(array, obj, iterator) {
|
||||
iterator || (iterator = _.identity);
|
||||
var value = iterator(obj);
|
||||
_.sortedIndex = function(array, obj, iterator, context) {
|
||||
iterator = iterator == null ? _.identity : lookupIterator(iterator);
|
||||
var value = iterator.call(context, obj);
|
||||
var low = 0, high = array.length;
|
||||
while (low < high) {
|
||||
var mid = (low + high) >> 1;
|
||||
iterator(array[mid]) < value ? low = mid + 1 : high = mid;
|
||||
var mid = (low + high) >>> 1;
|
||||
iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;
|
||||
}
|
||||
return low;
|
||||
};
|
||||
|
||||
// Safely convert anything iterable into a real, live array.
|
||||
_.toArray = function(obj) {
|
||||
if (!obj) return [];
|
||||
if (_.isArray(obj) || _.isArguments(obj)) return slice.call(obj);
|
||||
if (_.isFunction(obj.toArray)) return obj.toArray();
|
||||
if (!obj) return [];
|
||||
if (obj.length === +obj.length) return slice.call(obj);
|
||||
return _.values(obj);
|
||||
};
|
||||
|
||||
// Return the number of elements in an object.
|
||||
_.size = function(obj) {
|
||||
return _.isArray(obj) ? obj.length : _.keys(obj).length;
|
||||
if (obj == null) return 0;
|
||||
return (obj.length === +obj.length) ? obj.length : _.keys(obj).length;
|
||||
};
|
||||
|
||||
// Array Functions
|
||||
@@ -348,6 +377,7 @@
|
||||
// values in the array. Aliased as `head` and `take`. The **guard** check
|
||||
// allows it to work with `_.map`.
|
||||
_.first = _.head = _.take = function(array, n, guard) {
|
||||
if (array == null) return void 0;
|
||||
return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
|
||||
};
|
||||
|
||||
@@ -362,6 +392,7 @@
|
||||
// Get the last element of an array. Passing **n** will return the last N
|
||||
// values in the array. The **guard** check allows it to work with `_.map`.
|
||||
_.last = function(array, n, guard) {
|
||||
if (array == null) return void 0;
|
||||
if ((n != null) && !guard) {
|
||||
return slice.call(array, Math.max(array.length - n, 0));
|
||||
} else {
|
||||
@@ -369,12 +400,12 @@
|
||||
}
|
||||
};
|
||||
|
||||
// Returns everything but the first entry of the array. Aliased as `tail`.
|
||||
// Especially useful on the arguments object. Passing an **index** will return
|
||||
// the rest of the values in the array from that index onward. The **guard**
|
||||
// Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
|
||||
// Especially useful on the arguments object. Passing an **n** will return
|
||||
// the rest N values in the array. The **guard**
|
||||
// check allows it to work with `_.map`.
|
||||
_.rest = _.tail = function(array, index, guard) {
|
||||
return slice.call(array, (index == null) || guard ? 1 : index);
|
||||
_.rest = _.tail = _.drop = function(array, n, guard) {
|
||||
return slice.call(array, (n == null) || guard ? 1 : n);
|
||||
};
|
||||
|
||||
// Trim out all falsy values from an array.
|
||||
@@ -407,23 +438,23 @@
|
||||
// Produce a duplicate-free version of the array. If the array has already
|
||||
// been sorted, you have the option of using a faster algorithm.
|
||||
// Aliased as `unique`.
|
||||
_.uniq = _.unique = function(array, isSorted, iterator) {
|
||||
var initial = iterator ? _.map(array, iterator) : array;
|
||||
_.uniq = _.unique = function(array, isSorted, iterator, context) {
|
||||
var initial = iterator ? _.map(array, iterator, context) : array;
|
||||
var results = [];
|
||||
_.reduce(initial, function(memo, value, index) {
|
||||
if (isSorted ? (_.last(memo) !== value || !memo.length) : !_.include(memo, value)) {
|
||||
memo.push(value);
|
||||
var seen = [];
|
||||
each(initial, function(value, index) {
|
||||
if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) {
|
||||
seen.push(value);
|
||||
results.push(array[index]);
|
||||
}
|
||||
return memo;
|
||||
}, []);
|
||||
});
|
||||
return results;
|
||||
};
|
||||
|
||||
// Produce an array that contains the union: each distinct element from all of
|
||||
// the passed-in arrays.
|
||||
_.union = function() {
|
||||
return _.uniq(flatten(arguments, true, []));
|
||||
return _.uniq(concat.apply(ArrayProto, arguments));
|
||||
};
|
||||
|
||||
// Produce an array that contains every item shared between all the
|
||||
@@ -440,8 +471,8 @@
|
||||
// Take the difference between one array and a number of other arrays.
|
||||
// Only the elements present in just the first array will remain.
|
||||
_.difference = function(array) {
|
||||
var rest = flatten(slice.call(arguments, 1), true, []);
|
||||
return _.filter(array, function(value){ return !_.include(rest, value); });
|
||||
var rest = concat.apply(ArrayProto, slice.call(arguments, 1));
|
||||
return _.filter(array, function(value){ return !_.contains(rest, value); });
|
||||
};
|
||||
|
||||
// Zip together multiple lists into a single array -- elements that share
|
||||
@@ -456,12 +487,18 @@
|
||||
return results;
|
||||
};
|
||||
|
||||
// Zip together two arrays -- an array of keys and an array of values -- into
|
||||
// a single object.
|
||||
_.zipObject = function(keys, values) {
|
||||
// Converts lists into objects. Pass either a single array of `[key, value]`
|
||||
// pairs, or two parallel arrays of the same length -- one of keys, and one of
|
||||
// the corresponding values.
|
||||
_.object = function(list, values) {
|
||||
if (list == null) return {};
|
||||
var result = {};
|
||||
for (var i = 0, l = keys.length; i < l; i++) {
|
||||
result[keys[i]] = values[i];
|
||||
for (var i = 0, l = list.length; i < l; i++) {
|
||||
if (values) {
|
||||
result[list[i]] = values[i];
|
||||
} else {
|
||||
result[list[i][0]] = list[i][1];
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
@@ -474,21 +511,28 @@
|
||||
// for **isSorted** to use binary search.
|
||||
_.indexOf = function(array, item, isSorted) {
|
||||
if (array == null) return -1;
|
||||
var i, l;
|
||||
var i = 0, l = array.length;
|
||||
if (isSorted) {
|
||||
i = _.sortedIndex(array, item);
|
||||
return array[i] === item ? i : -1;
|
||||
if (typeof isSorted == 'number') {
|
||||
i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted);
|
||||
} else {
|
||||
i = _.sortedIndex(array, item);
|
||||
return array[i] === item ? i : -1;
|
||||
}
|
||||
}
|
||||
if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item);
|
||||
for (i = 0, l = array.length; i < l; i++) if (array[i] === item) return i;
|
||||
if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
|
||||
for (; i < l; i++) if (array[i] === item) return i;
|
||||
return -1;
|
||||
};
|
||||
|
||||
// Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
|
||||
_.lastIndexOf = function(array, item) {
|
||||
_.lastIndexOf = function(array, item, from) {
|
||||
if (array == null) return -1;
|
||||
if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item);
|
||||
var i = array.length;
|
||||
var hasIndex = from != null;
|
||||
if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {
|
||||
return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);
|
||||
}
|
||||
var i = (hasIndex ? from : array.length);
|
||||
while (i--) if (array[i] === item) return i;
|
||||
return -1;
|
||||
};
|
||||
@@ -575,23 +619,25 @@
|
||||
// Returns a function, that, when invoked, will only be triggered at most once
|
||||
// during a given window of time.
|
||||
_.throttle = function(func, wait) {
|
||||
var context, args, timeout, throttling, more, result;
|
||||
var whenDone = _.debounce(function(){ more = throttling = false; }, wait);
|
||||
var context, args, timeout, result;
|
||||
var previous = 0;
|
||||
var later = function() {
|
||||
previous = new Date;
|
||||
timeout = null;
|
||||
result = func.apply(context, args);
|
||||
};
|
||||
return function() {
|
||||
context = this; args = arguments;
|
||||
var later = function() {
|
||||
timeout = null;
|
||||
if (more) func.apply(context, args);
|
||||
whenDone();
|
||||
};
|
||||
if (!timeout) timeout = setTimeout(later, wait);
|
||||
if (throttling) {
|
||||
more = true;
|
||||
} else {
|
||||
throttling = true;
|
||||
var now = new Date;
|
||||
var remaining = wait - (now - previous);
|
||||
context = this;
|
||||
args = arguments;
|
||||
if (remaining <= 0) {
|
||||
clearTimeout(timeout);
|
||||
previous = now;
|
||||
result = func.apply(context, args);
|
||||
} else if (!timeout) {
|
||||
timeout = setTimeout(later, remaining);
|
||||
}
|
||||
whenDone();
|
||||
return result;
|
||||
};
|
||||
};
|
||||
@@ -601,17 +647,18 @@
|
||||
// N milliseconds. If `immediate` is passed, trigger the function on the
|
||||
// leading edge, instead of the trailing.
|
||||
_.debounce = function(func, wait, immediate) {
|
||||
var timeout;
|
||||
var timeout, result;
|
||||
return function() {
|
||||
var context = this, args = arguments;
|
||||
var later = function() {
|
||||
timeout = null;
|
||||
if (!immediate) func.apply(context, args);
|
||||
if (!immediate) result = func.apply(context, args);
|
||||
};
|
||||
var callNow = immediate && !timeout;
|
||||
clearTimeout(timeout);
|
||||
timeout = setTimeout(later, wait);
|
||||
if (callNow) func.apply(context, args);
|
||||
if (callNow) result = func.apply(context, args);
|
||||
return result;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -622,7 +669,9 @@
|
||||
return function() {
|
||||
if (ran) return memo;
|
||||
ran = true;
|
||||
return memo = func.apply(this, arguments);
|
||||
memo = func.apply(this, arguments);
|
||||
func = null;
|
||||
return memo;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -631,7 +680,8 @@
|
||||
// conditionally execute the original function.
|
||||
_.wrap = function(func, wrapper) {
|
||||
return function() {
|
||||
var args = [func].concat(slice.call(arguments, 0));
|
||||
var args = [func];
|
||||
push.apply(args, arguments);
|
||||
return wrapper.apply(this, args);
|
||||
};
|
||||
};
|
||||
@@ -673,7 +723,23 @@
|
||||
|
||||
// Retrieve the values of an object's properties.
|
||||
_.values = function(obj) {
|
||||
return _.map(obj, _.identity);
|
||||
var values = [];
|
||||
for (var key in obj) if (_.has(obj, key)) values.push(obj[key]);
|
||||
return values;
|
||||
};
|
||||
|
||||
// Convert an object into a list of `[key, value]` pairs.
|
||||
_.pairs = function(obj) {
|
||||
var pairs = [];
|
||||
for (var key in obj) if (_.has(obj, key)) pairs.push([key, obj[key]]);
|
||||
return pairs;
|
||||
};
|
||||
|
||||
// Invert the keys and values of an object. The values must be serializable.
|
||||
_.invert = function(obj) {
|
||||
var result = {};
|
||||
for (var key in obj) if (_.has(obj, key)) result[obj[key]] = key;
|
||||
return result;
|
||||
};
|
||||
|
||||
// Return a sorted list of the function names available on the object.
|
||||
@@ -699,7 +765,7 @@
|
||||
// Return a copy of the object only containing the whitelisted properties.
|
||||
_.pick = function(obj) {
|
||||
var copy = {};
|
||||
var keys = _.flatten(slice.call(arguments, 1));
|
||||
var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
|
||||
each(keys, function(key) {
|
||||
if (key in obj) copy[key] = obj[key];
|
||||
});
|
||||
@@ -709,9 +775,9 @@
|
||||
// Return a copy of the object without the blacklisted properties.
|
||||
_.omit = function(obj) {
|
||||
var copy = {};
|
||||
var keys = _.flatten(slice.call(arguments, 1));
|
||||
var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
|
||||
for (var key in obj) {
|
||||
if (!_.include(keys, key)) copy[key] = obj[key];
|
||||
if (!_.contains(keys, key)) copy[key] = obj[key];
|
||||
}
|
||||
return copy;
|
||||
};
|
||||
@@ -741,18 +807,15 @@
|
||||
};
|
||||
|
||||
// Internal recursive comparison function for `isEqual`.
|
||||
var eq = function(a, b, stack) {
|
||||
var eq = function(a, b, aStack, bStack) {
|
||||
// Identical objects are equal. `0 === -0`, but they aren't identical.
|
||||
// See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
|
||||
if (a === b) return a !== 0 || 1 / a == 1 / b;
|
||||
// A strict comparison is necessary because `null == undefined`.
|
||||
if (a == null || b == null) return a === b;
|
||||
// Unwrap any wrapped objects.
|
||||
if (a._chain) a = a._wrapped;
|
||||
if (b._chain) b = b._wrapped;
|
||||
// Invoke a custom `isEqual` method if one is provided.
|
||||
if (a.isEqual && _.isFunction(a.isEqual)) return a.isEqual(b);
|
||||
if (b.isEqual && _.isFunction(b.isEqual)) return b.isEqual(a);
|
||||
if (a instanceof _) a = a._wrapped;
|
||||
if (b instanceof _) b = b._wrapped;
|
||||
// Compare `[[Class]]` names.
|
||||
var className = toString.call(a);
|
||||
if (className != toString.call(b)) return false;
|
||||
@@ -782,14 +845,15 @@
|
||||
if (typeof a != 'object' || typeof b != 'object') return false;
|
||||
// Assume equality for cyclic structures. The algorithm for detecting cyclic
|
||||
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
|
||||
var length = stack.length;
|
||||
var length = aStack.length;
|
||||
while (length--) {
|
||||
// Linear search. Performance is inversely proportional to the number of
|
||||
// unique nested structures.
|
||||
if (stack[length] == a) return true;
|
||||
if (aStack[length] == a) return bStack[length] == b;
|
||||
}
|
||||
// Add the first object to the stack of traversed objects.
|
||||
stack.push(a);
|
||||
aStack.push(a);
|
||||
bStack.push(b);
|
||||
var size = 0, result = true;
|
||||
// Recursively compare objects and arrays.
|
||||
if (className == '[object Array]') {
|
||||
@@ -799,20 +863,24 @@
|
||||
if (result) {
|
||||
// Deep compare the contents, ignoring non-numeric properties.
|
||||
while (size--) {
|
||||
// Ensure commutative equality for sparse arrays.
|
||||
if (!(result = size in a == size in b && eq(a[size], b[size], stack))) break;
|
||||
if (!(result = eq(a[size], b[size], aStack, bStack))) break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Objects with different constructors are not equivalent.
|
||||
if ('constructor' in a != 'constructor' in b || a.constructor != b.constructor) return false;
|
||||
// Objects with different constructors are not equivalent, but `Object`s
|
||||
// from different frames are.
|
||||
var aCtor = a.constructor, bCtor = b.constructor;
|
||||
if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) &&
|
||||
_.isFunction(bCtor) && (bCtor instanceof bCtor))) {
|
||||
return false;
|
||||
}
|
||||
// Deep compare objects.
|
||||
for (var key in a) {
|
||||
if (_.has(a, key)) {
|
||||
// Count the expected number of properties.
|
||||
size++;
|
||||
// Deep compare each member.
|
||||
if (!(result = _.has(b, key) && eq(a[key], b[key], stack))) break;
|
||||
if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
|
||||
}
|
||||
}
|
||||
// Ensure that both objects contain the same number of properties.
|
||||
@@ -824,13 +892,14 @@
|
||||
}
|
||||
}
|
||||
// Remove the first object from the stack of traversed objects.
|
||||
stack.pop();
|
||||
aStack.pop();
|
||||
bStack.pop();
|
||||
return result;
|
||||
};
|
||||
|
||||
// Perform a deep comparison to check if two objects are equal.
|
||||
_.isEqual = function(a, b) {
|
||||
return eq(a, b, []);
|
||||
return eq(a, b, [], []);
|
||||
};
|
||||
|
||||
// Is a given array, string, or object empty?
|
||||
@@ -844,7 +913,7 @@
|
||||
|
||||
// Is a given value a DOM element?
|
||||
_.isElement = function(obj) {
|
||||
return !!(obj && obj.nodeType == 1);
|
||||
return !!(obj && obj.nodeType === 1);
|
||||
};
|
||||
|
||||
// Is a given value an array?
|
||||
@@ -873,15 +942,21 @@
|
||||
};
|
||||
}
|
||||
|
||||
// Optimize `isFunction` if appropriate.
|
||||
if (typeof (/./) !== 'function') {
|
||||
_.isFunction = function(obj) {
|
||||
return typeof obj === 'function';
|
||||
};
|
||||
}
|
||||
|
||||
// Is a given object a finite number?
|
||||
_.isFinite = function(obj) {
|
||||
return _.isNumber(obj) && isFinite(obj);
|
||||
return isFinite( obj ) && !isNaN( parseFloat(obj) );
|
||||
};
|
||||
|
||||
// Is the given value `NaN`?
|
||||
// Is the given value `NaN`? (NaN is the only number which does not equal itself).
|
||||
_.isNaN = function(obj) {
|
||||
// `NaN` is the only value for which `===` is not reflexive.
|
||||
return obj !== obj;
|
||||
return _.isNumber(obj) && obj != +obj;
|
||||
};
|
||||
|
||||
// Is a given value a boolean?
|
||||
@@ -925,25 +1000,43 @@
|
||||
for (var i = 0; i < n; i++) iterator.call(context, i);
|
||||
};
|
||||
|
||||
// Return a random integer between min and max (inclusive).
|
||||
_.random = function(min, max) {
|
||||
if (max == null) {
|
||||
max = min;
|
||||
min = 0;
|
||||
}
|
||||
return min + (0 | Math.random() * (max - min + 1));
|
||||
};
|
||||
|
||||
// List of HTML entities for escaping.
|
||||
var htmlEscapes = {
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'"': '"',
|
||||
"'": ''',
|
||||
'/': '/'
|
||||
var entityMap = {
|
||||
escape: {
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'"': '"',
|
||||
"'": ''',
|
||||
'/': '/'
|
||||
}
|
||||
};
|
||||
entityMap.unescape = _.invert(entityMap.escape);
|
||||
|
||||
// Regexes containing the keys and values listed immediately above.
|
||||
var entityRegexes = {
|
||||
escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'),
|
||||
unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g')
|
||||
};
|
||||
|
||||
// Regex containing the keys listed immediately above.
|
||||
var htmlEscaper = /[&<>"'\/]/g;
|
||||
|
||||
// Escape a string for HTML interpolation.
|
||||
_.escape = function(string) {
|
||||
return ('' + string).replace(htmlEscaper, function(match) {
|
||||
return htmlEscapes[match];
|
||||
});
|
||||
};
|
||||
// Functions for escaping and unescaping strings to/from HTML interpolation.
|
||||
_.each(['escape', 'unescape'], function(method) {
|
||||
_[method] = function(string) {
|
||||
if (string == null) return '';
|
||||
return ('' + string).replace(entityRegexes[method], function(match) {
|
||||
return entityMap[method][match];
|
||||
});
|
||||
};
|
||||
});
|
||||
|
||||
// If the value of the named property is a function then invoke it;
|
||||
// otherwise, return it.
|
||||
@@ -953,11 +1046,15 @@
|
||||
return _.isFunction(value) ? value.call(object) : value;
|
||||
};
|
||||
|
||||
// Add your own custom functions to the Underscore object, ensuring that
|
||||
// they're correctly added to the OOP wrapper as well.
|
||||
// Add your own custom functions to the Underscore object.
|
||||
_.mixin = function(obj) {
|
||||
each(_.functions(obj), function(name){
|
||||
addToWrapper(name, _[name] = obj[name]);
|
||||
var func = _[name] = obj[name];
|
||||
_.prototype[name] = function() {
|
||||
var args = [this._wrapped];
|
||||
push.apply(args, arguments);
|
||||
return result.call(this, func.apply(_, args));
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
@@ -980,63 +1077,63 @@
|
||||
// When customizing `templateSettings`, if you don't want to define an
|
||||
// interpolation, evaluation or escaping regex, we need one that is
|
||||
// guaranteed not to match.
|
||||
var noMatch = /.^/;
|
||||
var noMatch = /(.)^/;
|
||||
|
||||
// Certain characters need to be escaped so that they can be put into a
|
||||
// string literal.
|
||||
var escapes = {
|
||||
'\\': '\\',
|
||||
"'": "'",
|
||||
r: '\r',
|
||||
n: '\n',
|
||||
t: '\t',
|
||||
u2028: '\u2028',
|
||||
u2029: '\u2029'
|
||||
"'": "'",
|
||||
'\\': '\\',
|
||||
'\r': 'r',
|
||||
'\n': 'n',
|
||||
'\t': 't',
|
||||
'\u2028': 'u2028',
|
||||
'\u2029': 'u2029'
|
||||
};
|
||||
|
||||
for (var key in escapes) escapes[escapes[key]] = key;
|
||||
var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
|
||||
var unescaper = /\\(\\|'|r|n|t|u2028|u2029)/g;
|
||||
|
||||
// Within an interpolation, evaluation, or escaping, remove HTML escaping
|
||||
// that had been previously added.
|
||||
var unescape = function(code) {
|
||||
return code.replace(unescaper, function(match, escape) {
|
||||
return escapes[escape];
|
||||
});
|
||||
};
|
||||
|
||||
// JavaScript micro-templating, similar to John Resig's implementation.
|
||||
// Underscore templating handles arbitrary delimiters, preserves whitespace,
|
||||
// and correctly escapes quotes within interpolated code.
|
||||
_.template = function(text, data, settings) {
|
||||
settings = _.defaults(settings || {}, _.templateSettings);
|
||||
settings = _.defaults({}, settings, _.templateSettings);
|
||||
|
||||
// Compile the template source, taking care to escape characters that
|
||||
// cannot be included in a string literal and then unescape them in code
|
||||
// blocks.
|
||||
var source = "__p+='" + text
|
||||
.replace(escaper, function(match) {
|
||||
return '\\' + escapes[match];
|
||||
})
|
||||
.replace(settings.escape || noMatch, function(match, code) {
|
||||
return "'+\n((__t=(" + unescape(code) + "))==null?'':_.escape(__t))+\n'";
|
||||
})
|
||||
.replace(settings.interpolate || noMatch, function(match, code) {
|
||||
return "'+\n((__t=(" + unescape(code) + "))==null?'':__t)+\n'";
|
||||
})
|
||||
.replace(settings.evaluate || noMatch, function(match, code) {
|
||||
return "';\n" + unescape(code) + "\n__p+='";
|
||||
}) + "';\n";
|
||||
// Combine delimiters into one regular expression via alternation.
|
||||
var matcher = new RegExp([
|
||||
(settings.escape || noMatch).source,
|
||||
(settings.interpolate || noMatch).source,
|
||||
(settings.evaluate || noMatch).source
|
||||
].join('|') + '|$', 'g');
|
||||
|
||||
// Compile the template source, escaping string literals appropriately.
|
||||
var index = 0;
|
||||
var source = "__p+='";
|
||||
text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
|
||||
source += text.slice(index, offset)
|
||||
.replace(escaper, function(match) { return '\\' + escapes[match]; });
|
||||
source +=
|
||||
escape ? "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'" :
|
||||
interpolate ? "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'" :
|
||||
evaluate ? "';\n" + evaluate + "\n__p+='" : '';
|
||||
index = offset + match.length;
|
||||
});
|
||||
source += "';\n";
|
||||
|
||||
// If a variable is not specified, place data values in local scope.
|
||||
if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
|
||||
|
||||
source = "var __t,__p='',__j=Array.prototype.join," +
|
||||
"print=function(){__p+=__j.call(arguments,'')};\n" +
|
||||
"print=function(){__p+=__j.call(arguments,'');};\n" +
|
||||
source + "return __p;\n";
|
||||
|
||||
var render = new Function(settings.variable || 'obj', '_', source);
|
||||
try {
|
||||
var render = new Function(settings.variable || 'obj', '_', source);
|
||||
} catch (e) {
|
||||
e.source = source;
|
||||
throw e;
|
||||
}
|
||||
|
||||
if (data) return render(data, _);
|
||||
var template = function(data) {
|
||||
return render.call(this, data, _);
|
||||
@@ -1053,29 +1150,15 @@
|
||||
return _(obj).chain();
|
||||
};
|
||||
|
||||
// The OOP Wrapper
|
||||
// OOP
|
||||
// ---------------
|
||||
|
||||
// If Underscore is called as a function, it returns a wrapped object that
|
||||
// can be used OO-style. This wrapper holds altered versions of all the
|
||||
// underscore functions. Wrapped objects may be chained.
|
||||
var wrapper = function(obj) { this._wrapped = obj; };
|
||||
|
||||
// Expose `wrapper.prototype` as `_.prototype`
|
||||
_.prototype = wrapper.prototype;
|
||||
|
||||
// Helper function to continue chaining intermediate results.
|
||||
var result = function(obj, chain) {
|
||||
return chain ? _(obj).chain() : obj;
|
||||
};
|
||||
|
||||
// A method to easily add functions to the OOP wrapper.
|
||||
var addToWrapper = function(name, func) {
|
||||
wrapper.prototype[name] = function() {
|
||||
var args = slice.call(arguments);
|
||||
unshift.call(args, this._wrapped);
|
||||
return result(func.apply(_, args), this._chain);
|
||||
};
|
||||
var result = function(obj) {
|
||||
return this._chain ? _(obj).chain() : obj;
|
||||
};
|
||||
|
||||
// Add all of the Underscore functions to the wrapper object.
|
||||
@@ -1084,31 +1167,35 @@
|
||||
// Add all mutator Array functions to the wrapper.
|
||||
each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
|
||||
var method = ArrayProto[name];
|
||||
wrapper.prototype[name] = function() {
|
||||
_.prototype[name] = function() {
|
||||
var obj = this._wrapped;
|
||||
method.apply(obj, arguments);
|
||||
if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0];
|
||||
return result(obj, this._chain);
|
||||
return result.call(this, obj);
|
||||
};
|
||||
});
|
||||
|
||||
// Add all accessor Array functions to the wrapper.
|
||||
each(['concat', 'join', 'slice'], function(name) {
|
||||
var method = ArrayProto[name];
|
||||
wrapper.prototype[name] = function() {
|
||||
return result(method.apply(this._wrapped, arguments), this._chain);
|
||||
_.prototype[name] = function() {
|
||||
return result.call(this, method.apply(this._wrapped, arguments));
|
||||
};
|
||||
});
|
||||
|
||||
// Start chaining a wrapped Underscore object.
|
||||
wrapper.prototype.chain = function() {
|
||||
this._chain = true;
|
||||
return this;
|
||||
};
|
||||
_.extend(_.prototype, {
|
||||
|
||||
// Extracts the result from a wrapped and chained object.
|
||||
wrapper.prototype.value = function() {
|
||||
return this._wrapped;
|
||||
};
|
||||
// Start chaining a wrapped Underscore object.
|
||||
chain: function() {
|
||||
this._chain = true;
|
||||
return this;
|
||||
},
|
||||
|
||||
// Extracts the result from a wrapped and chained object.
|
||||
value: function() {
|
||||
return this._wrapped;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
}).call(this);
|
||||
|
||||
Reference in New Issue
Block a user