diff --git a/.github/workflows/cd.yml b/.github/workflows/cd.yml new file mode 100644 index 0000000..e624acf --- /dev/null +++ b/.github/workflows/cd.yml @@ -0,0 +1,71 @@ +# This workflow is like CI, but also builds the documentation and deploys to NPM +# and gh-pages. + +name: Continuous Deployment + +on: + push: + branches: [prepublish] + workflow_run: + workflows: [Prepublication staging] + types: [completed] + +jobs: + deploy: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + with: + ref: prepublish + - name: Use Node.js 14.x + uses: actions/setup-node@v1 + with: + node-version: 14.x + - name: Configure yarn cache path + run: yarn config set cache-folder ~/.yarn-cache + - name: Restore yarn cache + uses: actions/cache@v2 + with: + path: ~/.yarn-cache + key: yarn-cache-14.x + restore-keys: | + yarn-cache- + - name: Restore node_modules + uses: actions/cache@v2 + with: + path: node_modules + key: node-modules-14.x-${{ hashFiles('yarn.lock') }} + restore-keys: | + node-modules-14.x- + node-modules- + - name: Install dependencies + run: yarn + - name: Build dist files and docs and run the tests + run: yarn grunt dist docco tocdoc + - name: Commit the build output + uses: EndBug/add-and-commit@v5 + with: + add: dist/ index.html + message: Autocommit build output (continuous deployment) + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Publish to NPM + run: yarn publish + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + - name: Merge into gh-pages + uses: devmasx/merge-branch@v1.3.0 + with: + type: now + target_branch: gh-pages + github_token: ${{ secrets.GITHUB_TOKEN }} + - uses: actions/checkout@v2 + with: + ref: gh-pages + - name: Tag the release + uses: Klemensas/action-autotag@stable + with: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + tag_prefix: v diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..971c9d3 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,46 @@ +# This workflow will install the node_modules, build the source code and run tests across different versions of node +# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions + +name: Continuous Integration + +on: + push: + branches: [master] + pull_request: + +jobs: + build: + + runs-on: ubuntu-latest + + strategy: + matrix: + node-version: [10.x, 14.x] + + steps: + - uses: actions/checkout@v2 + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v1 + with: + node-version: ${{ matrix.node-version }} + - name: Configure yarn cache path + run: yarn config set cache-folder ~/.yarn-cache + - name: Restore yarn cache + uses: actions/cache@v2 + with: + path: ~/.yarn-cache + key: yarn-cache-${{ matrix.node-version }} + restore-keys: | + yarn-cache- + - name: Restore node_modules + uses: actions/cache@v2 + with: + path: node_modules + key: node-modules-${{ matrix.node-version }}-${{ hashFiles('yarn.lock') }} + restore-keys: | + node-modules-${{ matrix.node-version }}- + node-modules- + - name: Install dependencies + run: yarn + - name: Run linter, concat, minifier and tests + run: yarn dist diff --git a/.github/workflows/prepublish.yml b/.github/workflows/prepublish.yml new file mode 100644 index 0000000..7c00d10 --- /dev/null +++ b/.github/workflows/prepublish.yml @@ -0,0 +1,26 @@ +# As an alternative to a manual push to the prepublish branch, this workflow can +# be triggered on a release branch by assigning a special label to its pull +# request in order to set the CD circus in motion. + +name: Prepublication staging + +on: + pull_request: + types: [labeled] + # Would filter by branch here, but GH Actions wrongly decides not to + # trigger the workflow if we do this. + +jobs: + stage: + runs-on: ubuntu-latest + # Filtering by branch here instead. Credit due to @MiguelSavignano. + # https://github.com/devmasx/merge-branch/issues/11 + if: contains(github.event.pull_request.head.ref, 'release/') || contains(github.event.pull_request.head.ref, 'hotfix/') + steps: + - uses: actions/checkout@v2 + - name: Merge into prepublish + uses: devmasx/merge-branch@v1.3.0 + with: + label_name: ready to launch + target_branch: prepublish + github_token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore index 9ee2555..29d29ae 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,5 @@ examples/*.css examples/*.html examples/public bower_components/* +dist/ +/index.html diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index f714fc0..0000000 --- a/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js - -node_js: - - "0.10" \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b82a579..6662c08 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -10,28 +10,29 @@ Create your own fork of contrib where you can make your changes. ## 3. Install development dependencies -Make sure you have [Node.js][node] and the [grunt cli][cli] installed. Then install contrib's development dependencies with `npm install`. +Make sure you have [Node.js][node] and [Yarn][yarn] installed. Then install contrib's development dependencies with `yarn`. Note that these dependencies include the [Grunt CLI][cli] which we use for task automation. ## 4. Change the code Make your code changes, ensuring they adhere to the same [coding style as Underscore][style]. Do **not** edit the files in `dist/`. -Make any necessary updates to the qUnit tests found in `test/`. Run `grunt test` to catch any test failures or lint issues. You can also use `grunt watch:test` to get instant feedback each time you save a file. +Make any necessary updates to the qUnit tests found in `test/`. Run `yarn test` to catch any test failures or lint issues. You can also use `yarn grunt watch:test` to get instant feedback each time you save a file. ## 5. Update the docs Make any necessary documentation updates in `docs/`. Do **not** edit `index.html` directly. -After updating the docs, run `grunt tocdoc` to rebuild the `index.html` file. Visually inspect `index.html` in your browser to ensure the generated docs look nice. +After updating the docs, run `yarn tocdoc` to rebuild the `index.html` file. Visually inspect `index.html` in your browser to ensure the generated docs look nice. ## 6. Send a pull request Send a pull request to `documentcloud/underscore-contrib` for feedback. -If modifications are necessary, make the changes and rerun `grunt test` or `grunt tocdoc` as needed. +If modifications are necessary, make the changes and rerun `yarn test` or `yarn tocdoc` as needed. And hopefully your pull request will be merged by the core team! :-) [style]:https://github.com/documentcloud/underscore/blob/master/underscore.js [node]:http://nodejs.org/ -[cli]:http://gruntjs.com/getting-started#installing-the-cli \ No newline at end of file +[yarn]:https://classic.yarnpkg.com/ +[cli]:http://gruntjs.com/getting-started#installing-the-cli diff --git a/DEPLOYING.md b/DEPLOYING.md new file mode 100644 index 0000000..8148e18 --- /dev/null +++ b/DEPLOYING.md @@ -0,0 +1,49 @@ +# How to cut a new release for Underscore-contrib + +This is a checklist for repository maintainers. It covers all the steps involved in releasing a new version, including publishing to NPM and updating the `gh-pages` branch. We have tried to automate as many of these steps as possible using GitHub Actions. The workflows involved are in the (hidden) `.github` directory. + +A "regular" release includes new changes that were introduced to the `master` branch since the previous release. A *hotfix* release instead skips any such changes and only addresses urgent problems with the previous release. + + +## Steps + +1. Ensure your local `master` branch descends from the previous release branch and that it is in a state that you want to release. **Exception:** for hotfixes, ensure you have an up-to-date local copy of the previous release branch instead. +2. Decide on the next version number, respecting [semver][semver]. For the sake of example we'll use `1.2.3` as a placeholder version throughout this checklist. +3. Create a `release/1.2.3` branch based on `master`. **Exception:** if this is a hotfix, start from the previous release branch instead and call it `hotfix/1.2.3`. +4. Bump the version number in the `package.json` and the `yarn.lock` by running the command `yarn version --no-git-tag-version`, with the extra flag `--major`, `--minor` or `--patch` depending on which part of the version number you're incrementing (e.g., `--patch` if you're bumping from 1.2.2 to 1.2.3). Note that you can configure `yarn` to always include the `--no-git-tag-version` flag so you don't have to type it every time. +5. Bump the version number in the source code and in `docs/index.md` accordingly. +6. Commit the changes from steps 4 and 5 with a commit message of the format `Bump the version to 1.2.3`. +7. Add more commits to extend the change log and to update any other documentation that might require it. Ensure that all documentation looks good. +8. Push the release branch and create a pull request against `master` (also if it is a hotfix). +9. At your option, have the release branch reviewed and add more commits to satisfy any change requests. +10. The "Continuous Integration" workflow will trigger automatically on the pull request. This runs the test suite against multiple environments. Wait for all checks to complete. +11. If any checks fail, add more commits to fix and repeat from step 10. +12. When all reviewers are satisfied and all checks pass, apply the "ready to launch" label to the pull request. This will trigger the "Prepublication staging" workflow, which will merge the release branch into the `prepublish` branch. Merge manually if the workflow fails for whatever reason. **Note:** do *not* merge into `master` yet. +13. The merging of new changes into `prepublish` will trigger the "Continuous Deployment" workflow, which is documented below. **Pay attention as the deployment workflow progresses.** +14. If the deployment workflow fails, identify the failing step and address as quickly as possible. Possible solution steps include: + - Adding new commits to the release branch and repeating from step 12 (most likely if the docs fail to build for some reason). + - Manually pushing new commits to the `prepublish` branch and repeating from step 13 (this might be needed in case of merge conflicts, although this is highly unlikely). + - Manually running `yarn publish` (if something is wrong with the NPM registry or the authentication credentials). + - Manually merging `prepublish` into `gh-pages` (in unlikely case of merge conflicts). + - Manually tagging the release on `gh-pages`. +15. When the deployment workflow has completed, double-check that the new version was published to NPM, that the website was updated and that the repository contains a tag for the new release. +16. Finally merge the release branch into `master`, but keep the branch around for a few days in case you need to do a hotfix. +17. Delete the release branch. You can still restore it if necessary, by tracing the history graph two commits back from the release tag. + + +## Automated continuous deployment workflow + +This workflow is defined in `.github/workflows/cd.yml`. Note that roughly the first half of the steps in that file consists of basic boilerplate to check out the source and install dependencies. + +The publishing to NPM depends on a [secret][secrets] named `NPM_TOKEN`, representing the API token of the NPM account that owns the `underscore-contrib` package. Only admins of the documentcloud organization can access this setting. + +1. Checkout the source, restore caches and install the dependencies. +2. Run `yarn grunt dist docco tocdoc`. +3. Commit the output of the previous step to the `prepublish` branch. +4. Publish to NPM. +5. Merge the `prepublish` branch into `gh-pages`. +6. Tag the tip of `gh-pages` with the version number in the `package.json`. + + +[semver]: https://semver.org +[secrets]: https://docs.github.com/en/free-pro-team@latest/actions/reference/encrypted-secrets diff --git a/Gruntfile.js b/Gruntfile.js index 70c0532..b0f4a96 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -88,8 +88,8 @@ module.exports = function(grunt) { } }); - grunt.registerTask("test", ["jshint", "qunit:main"]); - grunt.registerTask("dist", ["concat", "uglify"]); + grunt.registerTask('test', ['jshint', 'qunit:main']); grunt.registerTask('default', ['test']); grunt.registerTask('dist', ['test', 'concat', 'qunit:concat', 'uglify', 'qunit:min']); + grunt.registerTask('doc', ['test', 'tocdoc']); }; diff --git a/dist/underscore-contrib.js b/dist/underscore-contrib.js deleted file mode 100644 index 036e06a..0000000 --- a/dist/underscore-contrib.js +++ /dev/null @@ -1,2067 +0,0 @@ -// underscore-contrib v0.3.0 -// ========================= - -// > https://github.com/documentcloud/underscore-contrib -// > (c) 2013 Michael Fogus, DocumentCloud and Investigative Reporters & Editors -// > underscore-contrib may be freely distributed under the MIT license. - -// Underscore-contrib (underscore.array.builders.js 0.3.0) -// (c) 2013 Michael Fogus, DocumentCloud and Investigative Reporters & Editors -// Underscore-contrib may be freely distributed under the MIT license. - -(function(root) { - - // Baseline setup - // -------------- - - // Establish the root object, `window` in the browser, or `global` on the server. - var _ = root._ || require('underscore'); - - // Helpers - // ------- - - // Create quick reference variables for speed access to core prototypes. - var slice = Array.prototype.slice, - concat = Array.prototype.concat; - - var existy = function(x) { return x != null; }; - - // Mixing in the array builders - // ---------------------------- - - _.mixin({ - // Concatenates one or more arrays given as arguments. If given objects and - // scalars as arguments `cat` will plop them down in place in the result - // array. If given an `arguments` object, `cat` will treat it like an array - // and concatenate it likewise. - cat: function() { - return _.reduce(arguments, function(acc, elem) { - if (_.isArguments(elem)) { - return concat.call(acc, slice.call(elem)); - } - else { - return concat.call(acc, elem); - } - }, []); - }, - - // 'Constructs' an array by putting an element at its front - cons: function(head, tail) { - return _.cat([head], tail); - }, - - // Takes an array and chunks it some number of times into - // sub-arrays of size n. Allows and optional padding array as - // the third argument to fill in the tail chunk when n is - // not sufficient to build chunks of the same size. - chunk: function(array, n, pad) { - var p = function(array) { - if (array == null) return []; - - var part = _.take(array, n); - - if (n === _.size(part)) { - return _.cons(part, p(_.drop(array, n))); - } - else { - return pad ? [_.take(_.cat(part, pad), n)] : []; - } - }; - - return p(array); - }, - - // Takes an array and chunks it some number of times into - // sub-arrays of size n. If the array given cannot fill the size - // needs of the final chunk then a smaller chunk is used - // for the last. - chunkAll: function(array, n, step) { - step = (step != null) ? step : n; - - var p = function(array, n, step) { - if (_.isEmpty(array)) return []; - - return _.cons(_.take(array, n), - p(_.drop(array, step), n, step)); - }; - - return p(array, n, step); - }, - - // Maps a function over an array and concatenates all of the results. - mapcat: function(array, fun) { - return _.cat.apply(null, _.map(array, fun)); - }, - - // Returns an array with some item between each element - // of a given array. - interpose: function(array, inter) { - if (!_.isArray(array)) throw new TypeError; - var sz = _.size(array); - if (sz === 0) return array; - if (sz === 1) return array; - - return slice.call(_.mapcat(array, function(elem) { - return _.cons(elem, [inter]); - }), 0, -1); - }, - - // Weaves two or more arrays together - weave: function(/* args */) { - if (!_.some(arguments)) return []; - if (arguments.length == 1) return arguments[0]; - - return _.filter(_.flatten(_.zip.apply(null, arguments), true), function(elem) { - return elem != null; - }); - }, - interleave: _.weave, - - // Returns an array of a value repeated a certain number of - // times. - repeat: function(t, elem) { - return _.times(t, function() { return elem; }); - }, - - // Returns an array built from the contents of a given array repeated - // a certain number of times. - cycle: function(t, elems) { - return _.flatten(_.times(t, function() { return elems; }), true); - }, - - // Returns an array with two internal arrays built from - // taking an original array and spliting it at an index. - splitAt: function(array, index) { - return [_.take(array, index), _.drop(array, index)]; - }, - - // Call a function recursively f(f(f(args))) until a second - // given function goes falsey. Expects a seed value to start. - iterateUntil: function(doit, checkit, seed) { - var ret = []; - var result = doit(seed); - - while (checkit(result)) { - ret.push(result); - result = doit(result); - } - - return ret; - }, - - // Takes every nth item from an array, returning an array of - // the results. - takeSkipping: function(array, n) { - var ret = []; - var sz = _.size(array); - - if (n <= 0) return []; - if (n === 1) return array; - - for(var index = 0; index < sz; index += n) { - ret.push(array[index]); - } - - return ret; - }, - - // Returns an array of each intermediate stage of a call to - // a `reduce`-like function. - reductions: function(array, fun, init) { - var ret = []; - var acc = init; - - _.each(array, function(v,k) { - acc = fun(acc, array[k]); - ret.push(acc); - }); - - return ret; - }, - - // Runs its given function on the index of the elements rather than - // the elements themselves, keeping all of the truthy values in the end. - keepIndexed: function(array, pred) { - return _.filter(_.map(_.range(_.size(array)), function(i) { - return pred(i, array[i]); - }), - existy); - }, - - // Accepts an array-like object (other than strings) as an argument and - // returns an array whose elements are in the reverse order. Unlike the - // built-in `Array.prototype.reverse` method, this does not mutate the - // original object. Note: attempting to use this method on a string will - // result in a `TypeError`, as it cannot properly reverse unicode strings. - - reverseOrder: function(obj) { - if (typeof obj == 'string') - throw new TypeError('Strings cannot be reversed by _.reverseOrder'); - return slice.call(obj).reverse(); - } - }); - -})(this); - -// Underscore-contrib (underscore.array.selectors.js 0.3.0) -// (c) 2013 Michael Fogus, DocumentCloud and Investigative Reporters & Editors -// Underscore-contrib may be freely distributed under the MIT license. - -(function(root) { - - // Baseline setup - // -------------- - - // Establish the root object, `window` in the browser, or `global` on the server. - var _ = root._ || require('underscore'); - - // Helpers - // ------- - - // Create quick reference variables for speed access to core prototypes. - var slice = Array.prototype.slice, - concat = Array.prototype.concat; - - var existy = function(x) { return x != null; }; - var truthy = function(x) { return (x !== false) && existy(x); }; - var isSeq = function(x) { return (_.isArray(x)) || (_.isArguments(x)); }; - - // Mixing in the array selectors - // ---------------------------- - - _.mixin({ - // Returns the second element of an array. Passing **n** will return all but - // the first of the head N values in the array. The **guard** check allows it - // to work with `_.map`. - second: function(array, n, guard) { - if (array == null) return void 0; - return (n != null) && !guard ? slice.call(array, 1, n) : array[1]; - }, - - // Returns the third element of an array. Passing **n** will return all but - // the first two of the head N values in the array. The **guard** check allows it - // to work with `_.map`. - third: function(array, n, guard) { - if (array == null) return void 0; - return (n != null) && !guard ? slice.call(array, 2, n) : array[2]; - }, - - // A function to get at an index into an array - nth: function(array, index, guard) { - if ((index != null) && !guard) return array[index]; - }, - - // Takes all items in an array while a given predicate returns truthy. - takeWhile: function(array, pred) { - if (!isSeq(array)) throw new TypeError; - - var sz = _.size(array); - - for (var index = 0; index < sz; index++) { - if(!truthy(pred(array[index]))) { - break; - } - } - - return _.take(array, index); - }, - - // Drops all items from an array while a given predicate returns truthy. - dropWhile: function(array, pred) { - if (!isSeq(array)) throw new TypeError; - - var sz = _.size(array); - - for (var index = 0; index < sz; index++) { - if(!truthy(pred(array[index]))) - break; - } - - return _.drop(array, index); - }, - - // Returns an array with two internal arrays built from - // taking an original array and spliting it at the index - // where a given function goes falsey. - splitWith: function(array, pred) { - return [_.takeWhile(array, pred), _.dropWhile(array, pred)]; - }, - - // Takes an array and partitions it as the given predicate changes - // truth sense. - partitionBy: function(array, fun){ - if (_.isEmpty(array) || !existy(array)) return []; - - var fst = _.first(array); - var fstVal = fun(fst); - var run = concat.call([fst], _.takeWhile(_.rest(array), function(e) { - return _.isEqual(fstVal, fun(e)); - })); - - return concat.call([run], _.partitionBy(_.drop(array, _.size(run)), fun)); - }, - - // Returns the 'best' value in an array based on the result of a - // given function. - best: function(array, fun) { - return _.reduce(array, function(x, y) { - return fun(x, y) ? x : y; - }); - }, - - // Returns an array of existy results of a function over an source array. - keep: function(array, fun) { - if (!isSeq(array)) throw new TypeError("expected an array as the first argument"); - - return _.filter(_.map(array, function(e) { - return fun(e); - }), existy); - } - }); - -})(this); - -// Underscore-contrib (underscore.collections.walk.js 0.3.0) -// (c) 2013 Patrick Dubroy -// Underscore-contrib may be freely distributed under the MIT license. - -(function(root) { - - // Baseline setup - // -------------- - - // Establish the root object, `window` in the browser, or `global` on the server. - var _ = root._ || require('underscore'); - - // Helpers - // ------- - - // An internal object that can be returned from a visitor function to - // prevent a top-down walk from walking subtrees of a node. - var stopRecursion = {}; - - // An internal object that can be returned from a visitor function to - // cause the walk to immediately stop. - var stopWalk = {}; - - var notTreeError = 'Not a tree: same object found in two different branches'; - - // Implements the default traversal strategy: if `obj` is a DOM node, walk - // its DOM children; otherwise, walk all the objects it references. - function defaultTraversal(obj) { - return _.isElement(obj) ? obj.children : obj; - } - - // Walk the tree recursively beginning with `root`, calling `beforeFunc` - // before visiting an objects descendents, and `afterFunc` afterwards. - // If `collectResults` is true, the last argument to `afterFunc` will be a - // collection of the results of walking the node's subtrees. - function walkImpl(root, traversalStrategy, beforeFunc, afterFunc, context, collectResults) { - var visited = []; - return (function _walk(value, key, parent) { - // Keep track of objects that have been visited, and throw an exception - // when trying to visit the same object twice. - if (_.isObject(value)) { - if (visited.indexOf(value) >= 0) throw new TypeError(notTreeError); - visited.push(value); - } - - if (beforeFunc) { - var result = beforeFunc.call(context, value, key, parent); - if (result === stopWalk) return stopWalk; - if (result === stopRecursion) return; - } - - var subResults; - var target = traversalStrategy(value); - if (_.isObject(target) && !_.isEmpty(target)) { - // If collecting results from subtrees, collect them in the same shape - // as the parent node. - if (collectResults) subResults = _.isArray(value) ? [] : {}; - - var stop = _.any(target, function(obj, key) { - var result = _walk(obj, key, value); - if (result === stopWalk) return true; - if (subResults) subResults[key] = result; - }); - if (stop) return stopWalk; - } - if (afterFunc) return afterFunc.call(context, value, key, parent, subResults); - })(root); - } - - // Internal helper providing the implementation for `pluck` and `pluckRec`. - function pluck(obj, propertyName, recursive) { - var results = []; - this.preorder(obj, function(value, key) { - if (!recursive && key == propertyName) - return stopRecursion; - if (_.has(value, propertyName)) - results[results.length] = value[propertyName]; - }); - return results; - } - - var exports = { - // Performs a preorder traversal of `obj` and returns the first value - // which passes a truth test. - find: function(obj, visitor, context) { - var result; - this.preorder(obj, function(value, key, parent) { - if (visitor.call(context, value, key, parent)) { - result = value; - return stopWalk; - } - }, context); - return result; - }, - - // Recursively traverses `obj` and returns all the elements that pass a - // truth test. `strategy` is the traversal function to use, e.g. `preorder` - // or `postorder`. - filter: function(obj, strategy, visitor, context) { - var results = []; - if (obj == null) return results; - strategy(obj, function(value, key, parent) { - if (visitor.call(context, value, key, parent)) results.push(value); - }, null, this._traversalStrategy); - return results; - }, - - // Recursively traverses `obj` and returns all the elements for which a - // truth test fails. - reject: function(obj, strategy, visitor, context) { - return this.filter(obj, strategy, function(value, key, parent) { - return !visitor.call(context, value, key, parent); - }); - }, - - // Produces a new array of values by recursively traversing `obj` and - // mapping each value through the transformation function `visitor`. - // `strategy` is the traversal function to use, e.g. `preorder` or - // `postorder`. - map: function(obj, strategy, visitor, context) { - var results = []; - strategy(obj, function(value, key, parent) { - results[results.length] = visitor.call(context, value, key, parent); - }, null, this._traversalStrategy); - return results; - }, - - // Return the value of properties named `propertyName` reachable from the - // tree rooted at `obj`. Results are not recursively searched; use - // `pluckRec` for that. - pluck: function(obj, propertyName) { - return pluck.call(this, obj, propertyName, false); - }, - - // Version of `pluck` which recursively searches results for nested objects - // with a property named `propertyName`. - pluckRec: function(obj, propertyName) { - return pluck.call(this, obj, propertyName, true); - }, - - // Recursively traverses `obj` in a depth-first fashion, invoking the - // `visitor` function for each object only after traversing its children. - // `traversalStrategy` is intended for internal callers, and is not part - // of the public API. - postorder: function(obj, visitor, context, traversalStrategy) { - traversalStrategy = traversalStrategy || this._traversalStrategy; - walkImpl(obj, traversalStrategy, null, visitor, context); - }, - - // Recursively traverses `obj` in a depth-first fashion, invoking the - // `visitor` function for each object before traversing its children. - // `traversalStrategy` is intended for internal callers, and is not part - // of the public API. - preorder: function(obj, visitor, context, traversalStrategy) { - traversalStrategy = traversalStrategy || this._traversalStrategy; - walkImpl(obj, traversalStrategy, visitor, null, context); - }, - - // Builds up a single value by doing a post-order traversal of `obj` and - // calling the `visitor` function on each object in the tree. For leaf - // objects, the `memo` argument to `visitor` is the value of the `leafMemo` - // argument to `reduce`. For non-leaf objects, `memo` is a collection of - // the results of calling `reduce` on the object's children. - reduce: function(obj, visitor, leafMemo, context) { - var reducer = function(value, key, parent, subResults) { - return visitor(subResults || leafMemo, value, key, parent); - }; - return walkImpl(obj, this._traversalStrategy, null, reducer, context, true); - } - }; - - // Set up aliases to match those in underscore.js. - exports.collect = exports.map; - exports.detect = exports.find; - exports.select = exports.filter; - - // Returns an object containing the walk functions. If `traversalStrategy` - // is specified, it is a function determining how objects should be - // traversed. Given an object, it returns the object to be recursively - // walked. The default strategy is equivalent to `_.identity` for regular - // objects, and for DOM nodes it returns the node's DOM children. - _.walk = function(traversalStrategy) { - var walker = _.clone(exports); - - // Bind all of the public functions in the walker to itself. This allows - // the traversal strategy to be dynamically scoped. - _.bindAll.apply(null, [walker].concat(_.keys(walker))); - - walker._traversalStrategy = traversalStrategy || defaultTraversal; - return walker; - }; - - // Use `_.walk` as a namespace to hold versions of the walk functions which - // use the default traversal strategy. - _.extend(_.walk, _.walk()); -})(this); - -// Underscore-contrib (underscore.function.arity.js 0.3.0) -// (c) 2013 Michael Fogus, DocumentCloud and Investigative Reporters & Editors -// Underscore-contrib may be freely distributed under the MIT license. - -(function(root) { - - // Baseline setup - // -------------- - - // Establish the root object, `window` in the browser, or `global` on the server. - var _ = root._ || require('underscore'); - - // Helpers - // ------- - - function enforcesUnary (fn) { - return function mustBeUnary () { - if (arguments.length === 1) { - return fn.apply(this, arguments); - } - else throw new RangeError('Only a single argument may be accepted.'); - - }; - } - - // Curry - // ------- - var curry = (function () { - function collectArgs(func, that, argCount, args, newArg, reverse) { - if (reverse === true) { - args.unshift(newArg); - } else { - args.push(newArg); - } - if (args.length == argCount) { - return func.apply(that, args); - } else { - return enforcesUnary(function () { - return collectArgs(func, that, argCount, args.slice(0), arguments[0], reverse); - }); - } - } - return function curry (func, reverse) { - var that = this; - return enforcesUnary(function () { - return collectArgs(func, that, func.length, [], arguments[0], reverse); - }); - }; - }()); - - // Enforce Arity - // -------------------- - var enforce = (function () { - var CACHE = []; - return function enforce (func) { - if (typeof func !== 'function') { - throw new Error('Argument 1 must be a function.'); - } - var funcLength = func.length; - if (CACHE[funcLength] === undefined) { - CACHE[funcLength] = function (enforceFunc) { - return function () { - if (arguments.length !== funcLength) { - throw new RangeError(funcLength + ' arguments must be applied.'); - } - return enforceFunc.apply(this, arguments); - }; - }; - } - return CACHE[funcLength](func); - }; - }()); - - // Mixing in the arity functions - // ----------------------------- - - _.mixin({ - // ### Fixed arguments - - // Fixes the arguments to a function based on the parameter template defined by - // the presence of values and the `_` placeholder. - fix: function(fun) { - var fixArgs = _.rest(arguments); - - var f = function() { - var args = fixArgs.slice(); - var arg = 0; - - for ( var i = 0; i < (args.length || arg < arguments.length); i++ ) { - if ( args[i] === _ ) { - args[i] = arguments[arg++]; - } - } - - return fun.apply(null, args); - }; - - f._original = fun; - - return f; - }, - - unary: function (fun) { - return function unary (a) { - return fun.call(this, a); - }; - }, - - binary: function (fun) { - return function binary (a, b) { - return fun.call(this, a, b); - }; - }, - - ternary: function (fun) { - return function ternary (a, b, c) { - return fun.call(this, a, b, c); - }; - }, - - quaternary: function (fun) { - return function quaternary (a, b, c, d) { - return fun.call(this, a, b, c, d); - }; - }, - - // Flexible curry function with strict arity. - // Argument application left to right. - // source: https://github.com/eborden/js-curry - curry: curry, - - // Flexible right to left curry with strict arity. - rCurry: function (func) { - return curry.call(this, func, true); - }, - - - curry2: function (fun) { - return enforcesUnary(function curried (first) { - return enforcesUnary(function (last) { - return fun.call(this, first, last); - }); - }); - }, - - curry3: function (fun) { - return enforcesUnary(function (first) { - return enforcesUnary(function (second) { - return enforcesUnary(function (last) { - return fun.call(this, first, second, last); - }); - }); - }); - }, - - // reverse currying for functions taking two arguments. - rcurry2: function (fun) { - return enforcesUnary(function (last) { - return enforcesUnary(function (first) { - return fun.call(this, first, last); - }); - }); - }, - - rcurry3: function (fun) { - return enforcesUnary(function (last) { - return enforcesUnary(function (second) { - return enforcesUnary(function (first) { - return fun.call(this, first, second, last); - }); - }); - }); - }, - // Dynamic decorator to enforce function arity and defeat varargs. - enforce: enforce - }); - - _.arity = (function () { - // Allow 'new Function', as that is currently the only reliable way - // to manipulate function.length - /* jshint -W054 */ - var FUNCTIONS = {}; - return function arity (numberOfArgs, fun) { - if (FUNCTIONS[numberOfArgs] == null) { - var parameters = new Array(numberOfArgs); - for (var i = 0; i < numberOfArgs; ++i) { - parameters[i] = "__" + i; - } - var pstr = parameters.join(); - var code = "return function ("+pstr+") { return fun.apply(this, arguments); };"; - FUNCTIONS[numberOfArgs] = new Function(['fun'], code); - } - if (fun == null) { - return function (fun) { return arity(numberOfArgs, fun); }; - } - else return FUNCTIONS[numberOfArgs](fun); - }; - })(); - -})(this); - -// Underscore-contrib (underscore.function.combinators.js 0.3.0) -// (c) 2013 Michael Fogus, DocumentCloud and Investigative Reporters & Editors -// Underscore-contrib may be freely distributed under the MIT license. - -(function(root) { - - // Baseline setup - // -------------- - - // Establish the root object, `window` in the browser, or `global` on the server. - var _ = root._ || require('underscore'); - - // Helpers - // ------- - - var existy = function(x) { return x != null; }; - var truthy = function(x) { return (x !== false) && existy(x); }; - var __reverse = [].reverse; - var __slice = [].slice; - var __map = [].map; - var curry2 = function (fun) { - return function curried (first, optionalLast) { - if (arguments.length === 1) { - return function (last) { - return fun(first, last); - }; - } - else return fun(first, optionalLast); - }; - }; - - // n.b. depends on underscore.function.arity.js - - // Takes a target function and a mapping function. Returns a function - // that applies the mapper to its arguments before evaluating the body. - function baseMapArgs (fun, mapFun) { - return _.arity(fun.length, function () { - return fun.apply(this, __map.call(arguments, mapFun)); - }); - } - - // Mixing in the combinator functions - // ---------------------------------- - - _.mixin({ - // Provide "always" alias for backwards compatibility - always: _.constant, - - // Takes some number of functions, either as an array or variadically - // and returns a function that takes some value as its first argument - // and runs it through a pipeline of the original functions given. - pipeline: function(/*, funs */){ - var funs = (_.isArray(arguments[0])) ? arguments[0] : arguments; - - return function(seed) { - return _.reduce(funs, - function(l,r) { return r(l); }, - seed); - }; - }, - - // Composes a bunch of predicates into a single predicate that - // checks all elements of an array for conformance to all of the - // original predicates. - conjoin: function(/* preds */) { - var preds = arguments; - - return function(array) { - return _.every(array, function(e) { - return _.every(preds, function(p) { - return p(e); - }); - }); - }; - }, - - // Composes a bunch of predicates into a single predicate that - // checks all elements of an array for conformance to any of the - // original predicates. - disjoin: function(/* preds */) { - var preds = arguments; - - return function(array) { - return _.some(array, function(e) { - return _.some(preds, function(p) { - return p(e); - }); - }); - }; - }, - - // Takes a predicate-like and returns a comparator (-1,0,1). - comparator: function(fun) { - return function(x, y) { - if (truthy(fun(x, y))) - return -1; - else if (truthy(fun(y, x))) - return 1; - else - return 0; - }; - }, - - // Returns a function that reverses the sense of a given predicate-like. - complement: function(pred) { - return function() { - return !pred.apply(this, arguments); - }; - }, - - // Takes a function expecting varargs and - // returns a function that takes an array and - // uses its elements as the args to the original - // function - splat: function(fun) { - return function(array) { - return fun.apply(this, array); - }; - }, - - // Takes a function expecting an array and returns - // a function that takes varargs and wraps all - // in an array that is passed to the original function. - unsplat: function(fun) { - var funLength = fun.length; - - if (funLength < 1) { - return fun; - } - else if (funLength === 1) { - return function () { - return fun.call(this, __slice.call(arguments, 0)); - }; - } - else { - return function () { - var numberOfArgs = arguments.length, - namedArgs = __slice.call(arguments, 0, funLength - 1), - numberOfMissingNamedArgs = Math.max(funLength - numberOfArgs - 1, 0), - argPadding = new Array(numberOfMissingNamedArgs), - variadicArgs = __slice.call(arguments, fun.length - 1); - - return fun.apply(this, namedArgs.concat(argPadding).concat([variadicArgs])); - }; - } - }, - - // Same as unsplat, but the rest of the arguments are collected in the - // first parameter, e.g. unsplatl( function (args, callback) { ... ]}) - unsplatl: function(fun) { - var funLength = fun.length; - - if (funLength < 1) { - return fun; - } - else if (funLength === 1) { - return function () { - return fun.call(this, __slice.call(arguments, 0)); - }; - } - else { - return function () { - var numberOfArgs = arguments.length, - namedArgs = __slice.call(arguments, Math.max(numberOfArgs - funLength + 1, 0)), - variadicArgs = __slice.call(arguments, 0, Math.max(numberOfArgs - funLength + 1, 0)); - - return fun.apply(this, [variadicArgs].concat(namedArgs)); - }; - } - }, - - // map the arguments of a function - mapArgs: curry2(baseMapArgs), - - // Returns a function that returns an array of the calls to each - // given function for some arguments. - juxt: function(/* funs */) { - var funs = arguments; - - return function(/* args */) { - var args = arguments; - return _.map(funs, function(f) { - return f.apply(this, args); - }, this); - }; - }, - - // Returns a function that protects a given function from receiving - // non-existy values. Each subsequent value provided to `fnull` acts - // as the default to the original function should a call receive non-existy - // values in the defaulted arg slots. - fnull: function(fun /*, defaults */) { - var defaults = _.rest(arguments); - - return function(/*args*/) { - var args = _.toArray(arguments); - var sz = _.size(defaults); - - for(var i = 0; i < sz; i++) { - if (!existy(args[i])) - args[i] = defaults[i]; - } - - return fun.apply(this, args); - }; - }, - - // Flips the first two args of a function - flip2: function(fun) { - return function(/* args */) { - var flipped = __slice.call(arguments); - flipped[0] = arguments[1]; - flipped[1] = arguments[0]; - - return fun.apply(this, flipped); - }; - }, - - // Flips an arbitrary number of args of a function - flip: function(fun) { - return function(/* args */) { - var reversed = __reverse.call(arguments); - - return fun.apply(this, reversed); - }; - }, - - // Takes a method-style function (one which uses `this`) and pushes - // `this` into the argument list. The returned function uses its first - // argument as the receiver/context of the original function, and the rest - // of the arguments are used as the original's entire argument list. - functionalize: function(method) { - return function(ctx /*, args */) { - return method.apply(ctx, _.rest(arguments)); - }; - }, - - // Takes a function and pulls the first argument out of the argument - // list and into `this` position. The returned function calls the original - // with its receiver (`this`) prepending the argument list. The original - // is called with a receiver of `null`. - methodize: function(func) { - return function(/* args */) { - return func.apply(null, _.cons(this, arguments)); - }; - }, - - k: _.always, - t: _.pipeline - }); - - _.unsplatr = _.unsplat; - - // map the arguments of a function, takes the mapping function - // first so it can be used as a combinator - _.mapArgsWith = curry2(_.flip(baseMapArgs)); - - // Returns function property of object by name, bound to object - _.bound = function(obj, fname) { - var fn = obj[fname]; - if (!_.isFunction(fn)) - throw new TypeError("Expected property to be a function"); - return _.bind(fn, obj); - }; - -})(this); - -// Underscore-contrib (underscore.function.dispatch.js 0.3.0) -// (c) 2013 Justin Ridgewell -// Underscore-contrib may be freely distributed under the MIT license. - -(function(root) { - - // Baseline setup - // -------------- - - // Establish the root object, `window` in the browser, or `global` on the server. - var _ = root._ || require('underscore'); - - // Helpers - // ------- - - // Create quick reference variable for speed. - var slice = Array.prototype.slice; - - // Mixing in the attempt function - // ------------------------ - - _.mixin({ - // If object is not undefined or null then invoke the named `method` function - // with `object` as context and arguments; otherwise, return undefined. - attempt: function(object, method) { - if (object == null) return void 0; - var func = object[method]; - var args = slice.call(arguments, 2); - return _.isFunction(func) ? func.apply(object, args) : void 0; - } - }); - -})(this); - -// Underscore-contrib (underscore.function.iterators.js 0.3.0) -// (c) 2013 Michael Fogus and DocumentCloud Inc. -// Underscore-contrib may be freely distributed under the MIT license. - -(function(root, undefined) { - - // Baseline setup - // -------------- - - // Establish the root object, `window` in the browser, or `global` on the server. - var _ = root._ || require('underscore'); - - // Helpers - // ------- - - var HASNTBEENRUN = {}; - - function unary (fun) { - return function (first) { - return fun.call(this, first); - }; - } - - function binary (fun) { - return function (first, second) { - return fun.call(this, first, second); - }; - } - - // Mixing in the iterator functions - // -------------------------------- - - function foldl (iter, binaryFn, seed) { - var state, element; - if (seed !== void 0) { - state = seed; - } - else { - state = iter(); - } - element = iter(); - while (element != null) { - state = binaryFn.call(element, state, element); - element = iter(); - } - return state; - } - - function unfold (seed, unaryFn) { - var state = HASNTBEENRUN; - return function () { - if (state === HASNTBEENRUN) { - state = seed; - } else if (state != null) { - state = unaryFn.call(state, state); - } - - return state; - }; - } - - // note that the unfoldWithReturn behaves differently than - // unfold with respect to the first value returned - function unfoldWithReturn (seed, unaryFn) { - var state = seed, - pair, - value; - return function () { - if (state != null) { - pair = unaryFn.call(state, state); - value = pair[1]; - state = value != null ? pair[0] : void 0; - return value; - } - else return void 0; - }; - } - - function accumulate (iter, binaryFn, initial) { - var state = initial; - return function () { - var element = iter(); - if (element == null) { - return element; - } - else { - if (state === void 0) { - state = element; - } else { - state = binaryFn.call(element, state, element); - } - - return state; - } - }; - } - - function accumulateWithReturn (iter, binaryFn, initial) { - var state = initial, - stateAndReturnValue, - element; - return function () { - element = iter(); - if (element == null) { - return element; - } - else { - if (state === void 0) { - state = element; - return state; - } - else { - stateAndReturnValue = binaryFn.call(element, state, element); - state = stateAndReturnValue[0]; - return stateAndReturnValue[1]; - } - } - }; - } - - function map (iter, unaryFn) { - return function() { - var element; - element = iter(); - if (element != null) { - return unaryFn.call(element, element); - } else { - return void 0; - } - }; - } - - function mapcat(iter, unaryFn) { - var lastIter = null; - return function() { - var element; - var gen; - if (lastIter == null) { - gen = iter(); - if (gen == null) { - lastIter = null; - return void 0; - } - lastIter = unaryFn.call(gen, gen); - } - while (element == null) { - element = lastIter(); - if (element == null) { - gen = iter(); - if (gen == null) { - lastIter = null; - return void 0; - } - else { - lastIter = unaryFn.call(gen, gen); - } - } - } - return element; - }; - } - - function select (iter, unaryPredicateFn) { - return function() { - var element; - element = iter(); - while (element != null) { - if (unaryPredicateFn.call(element, element)) { - return element; - } - element = iter(); - } - return void 0; - }; - } - - function reject (iter, unaryPredicateFn) { - return select(iter, function (something) { - return !unaryPredicateFn(something); - }); - } - - function find (iter, unaryPredicateFn) { - return select(iter, unaryPredicateFn)(); - } - - function slice (iter, numberToDrop, numberToTake) { - var count = 0; - while (numberToDrop-- > 0) { - iter(); - } - if (numberToTake != null) { - return function() { - if (++count <= numberToTake) { - return iter(); - } else { - return void 0; - } - }; - } - else return iter; - } - - function drop (iter, numberToDrop) { - return slice(iter, numberToDrop == null ? 1 : numberToDrop); - } - - function take (iter, numberToTake) { - return slice(iter, 0, numberToTake == null ? 1 : numberToTake); - } - - function List (array) { - var index = 0; - return function() { - return array[index++]; - }; - } - - function Tree (array) { - var index, myself, state; - index = 0; - state = []; - myself = function() { - var element, tempState; - element = array[index++]; - if (element instanceof Array) { - state.push({ - array: array, - index: index - }); - array = element; - index = 0; - return myself(); - } else if (element === void 0) { - if (state.length > 0) { - tempState = state.pop(); - array = tempState.array; - index = tempState.index; - return myself(); - } else { - return void 0; - } - } else { - return element; - } - }; - return myself; - } - - function K (value) { - return function () { - return value; - }; - } - - function upRange (from, to, by) { - return function () { - var was; - - if (from > to) { - return void 0; - } - else { - was = from; - from = from + by; - return was; - } - }; - } - - function downRange (from, to, by) { - return function () { - var was; - - if (from < to) { - return void 0; - } - else { - was = from; - from = from - by; - return was; - } - }; - } - - function range (from, to, by) { - if (from == null) { - return upRange(1, Infinity, 1); - } - else if (to == null) { - return upRange(from, Infinity, 1); - } - else if (by == null) { - if (from <= to) { - return upRange(from, to, 1); - } - else return downRange(from, to, 1); - } - else if (by > 0) { - return upRange(from, to, by); - } - else if (by < 0) { - return downRange(from, to, Math.abs(by)); - } - else return k(from); - } - - var numbers = unary(range); - - _.iterators = { - accumulate: accumulate, - accumulateWithReturn: accumulateWithReturn, - foldl: foldl, - reduce: foldl, - unfold: unfold, - unfoldWithReturn: unfoldWithReturn, - map: map, - mapcat: mapcat, - select: select, - reject: reject, - filter: select, - find: find, - slice: slice, - drop: drop, - take: take, - List: List, - Tree: Tree, - constant: K, - K: K, - numbers: numbers, - range: range - }; - -})(this, void 0); - -// Underscore-contrib (underscore.function.predicates.js 0.3.0) -// (c) 2013 Michael Fogus, DocumentCloud and Investigative Reporters & Editors -// Underscore-contrib may be freely distributed under the MIT license. - -(function(root) { - - // Baseline setup - // -------------- - - // Establish the root object, `window` in the browser, or `global` on the server. - var _ = root._ || require('underscore'); - - // Helpers - // ------- - - - // Mixing in the predicate functions - // --------------------------------- - - _.mixin({ - // A wrapper around instanceof - isInstanceOf: function(x, t) { return (x instanceof t); }, - - // An associative object is one where its elements are - // accessed via a key or index. (i.e. array and object) - isAssociative: function(x) { return _.isArray(x) || _.isObject(x) || _.isArguments(x); }, - - // An indexed object is anything that allows numerical index for - // accessing its elements (e.g. arrays and strings). NOTE: Underscore - // does not support cross-browser consistent use of strings as array-like - // objects, so be wary in IE 8 when using String objects and IE<8. - // on string literals & objects. - isIndexed: function(x) { return _.isArray(x) || _.isString(x) || _.isArguments(x); }, - - // A seq is something considered a sequential composite type (i.e. arrays and `arguments`). - isSequential: function(x) { return (_.isArray(x)) || (_.isArguments(x)); }, - - // Check if an object is an object literal, since _.isObject(function() {}) === _.isObject([]) === true - isPlainObject: function(x) { return _.isObject(x) && x.constructor === root.Object; }, - - // These do what you think that they do - isZero: function(x) { return 0 === x; }, - isEven: function(x) { return _.isFinite(x) && (x & 1) === 0; }, - isOdd: function(x) { return _.isFinite(x) && !_.isEven(x); }, - isPositive: function(x) { return x > 0; }, - isNegative: function(x) { return x < 0; }, - isValidDate: function(x) { return _.isDate(x) && !_.isNaN(x.getTime()); }, - - // A numeric is a variable that contains a numeric value, regardless its type - // It can be a String containing a numeric value, exponential notation, or a Number object - // See here for more discussion: http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric/1830844#1830844 - isNumeric: function(n) { - return !isNaN(parseFloat(n)) && isFinite(n); - }, - - // An integer contains an optional minus sign to begin and only the digits 0-9 - // Objects that can be parsed that way are also considered ints, e.g. "123" - // Floats that are mathematically equal to integers are considered integers, e.g. 1.0 - // See here for more discussion: http://stackoverflow.com/questions/1019515/javascript-test-for-an-integer - isInteger: function(i) { - return _.isNumeric(i) && i % 1 === 0; - }, - - // A float is a numbr that is not an integer. - isFloat: function(n) { - return _.isNumeric(n) && !_.isInteger(n); - }, - - // checks if a string is a valid JSON - isJSON: function(str) { - try { - JSON.parse(str); - } catch (e) { - return false; - } - return true; - }, - - // Returns true if its arguments are monotonically - // increaing values; false otherwise. - isIncreasing: function() { - var count = _.size(arguments); - if (count === 1) return true; - if (count === 2) return arguments[0] < arguments[1]; - - for (var i = 1; i < count; i++) { - if (arguments[i-1] >= arguments[i]) { - return false; - } - } - - return true; - }, - - // Returns true if its arguments are monotonically - // decreaing values; false otherwise. - isDecreasing: function() { - var count = _.size(arguments); - if (count === 1) return true; - if (count === 2) return arguments[0] > arguments[1]; - - for (var i = 1; i < count; i++) { - if (arguments[i-1] <= arguments[i]) { - return false; - } - } - - return true; - } - }); - -})(this); - -// Underscore-contrib (underscore.object.builders.js 0.3.0) -// (c) 2013 Michael Fogus, DocumentCloud and Investigative Reporters & Editors -// Underscore-contrib may be freely distributed under the MIT license. - -(function(root) { - - // Baseline setup - // -------------- - - // Establish the root object, `window` in the browser, or `global` on the server. - var _ = root._ || require('underscore'); - - // Helpers - // ------- - - // Create quick reference variables for speed access to core prototypes. - var slice = Array.prototype.slice, - concat = Array.prototype.concat; - - var existy = function(x) { return x != null; }; - var truthy = function(x) { return (x !== false) && existy(x); }; - var isAssociative = function(x) { return _.isArray(x) || _.isObject(x); }; - var curry2 = function(fun) { - return function(last) { - return function(first) { - return fun(first, last); - }; - }; - }; - - // Mixing in the object builders - // ---------------------------- - - _.mixin({ - // Merges two or more objects starting with the left-most and - // applying the keys right-word - // {any:any}* -> {any:any} - merge: function(/* objs */){ - var dest = _.some(arguments) ? {} : null; - - if (truthy(dest)) { - _.extend.apply(null, concat.call([dest], _.toArray(arguments))); - } - - return dest; - }, - - // Takes an object and another object of strings to strings where the second - // object describes the key renaming to occur in the first object. - renameKeys: function(obj, kobj) { - return _.reduce(kobj, function(o, nu, old) { - if (existy(obj[old])) { - o[nu] = obj[old]; - return o; - } - else - return o; - }, - _.omit.apply(null, concat.call([obj], _.keys(kobj)))); - }, - - // Snapshots an object deeply. Based on the version by - // [Keith Devens](http://keithdevens.com/weblog/archive/2007/Jun/07/javascript.clone) - // until we can find a more efficient and robust way to do it. - snapshot: function(obj) { - if(obj == null || typeof(obj) != 'object') { - return obj; - } - - var temp = new obj.constructor(); - - for(var key in obj) { - if (obj.hasOwnProperty(key)) { - temp[key] = _.snapshot(obj[key]); - } - } - - return temp; - }, - - // Updates the value at any depth in a nested object based on the - // path described by the keys given. The function provided is supplied - // the current value and is expected to return a value for use as the - // new value. If no keys are provided, then the object itself is presented - // to the given function. - updatePath: function(obj, fun, ks, defaultValue) { - if (!isAssociative(obj)) throw new TypeError("Attempted to update a non-associative object."); - if (!existy(ks)) return fun(obj); - - var deepness = _.isArray(ks); - var keys = deepness ? ks : [ks]; - var ret = deepness ? _.snapshot(obj) : _.clone(obj); - var lastKey = _.last(keys); - var target = ret; - - _.each(_.initial(keys), function(key) { - if (defaultValue && !_.has(target, key)) { - target[key] = _.clone(defaultValue); - } - target = target[key]; - }); - - target[lastKey] = fun(target[lastKey]); - return ret; - }, - - // Sets the value at any depth in a nested object based on the - // path described by the keys given. - setPath: function(obj, value, ks, defaultValue) { - if (!existy(ks)) throw new TypeError("Attempted to set a property at a null path."); - - return _.updatePath(obj, function() { return value; }, ks, defaultValue); - }, - - // Returns an object where each element of an array is keyed to - // the number of times that it occurred in said array. - frequencies: curry2(_.countBy)(_.identity) - }); - -})(this); - -// Underscore-contrib (underscore.object.selectors.js 0.3.0) -// (c) 2013 Michael Fogus, DocumentCloud and Investigative Reporters & Editors -// Underscore-contrib may be freely distributed under the MIT license. - -(function(root) { - - // Baseline setup - // -------------- - - // Establish the root object, `window` in the browser, or `global` on the server. - var _ = root._ || require('underscore'); - - // Helpers - // ------- - - // Create quick reference variables for speed access to core prototypes. - var concat = Array.prototype.concat; - var ArrayProto = Array.prototype; - var slice = ArrayProto.slice; - - // Mixing in the object selectors - // ------------------------------ - - _.mixin({ - // Returns a function that will attempt to look up a named field - // in any object that it's given. - accessor: function(field) { - return function(obj) { - return (obj && obj[field]); - }; - }, - - // Given an object, returns a function that will attempt to look up a field - // that it's given. - dictionary: function (obj) { - return function(field) { - return (obj && field && obj[field]); - }; - }, - - // Like `_.pick` except that it takes an array of keys to pick. - selectKeys: function (obj, ks) { - return _.pick.apply(null, concat.call([obj], ks)); - }, - - // Returns the key/value pair for a given property in an object, undefined if not found. - kv: function(obj, key) { - if (_.has(obj, key)) { - return [key, obj[key]]; - } - - return void 0; - }, - - // Gets the value at any depth in a nested object based on the - // path described by the keys given. Keys may be given as an array - // or as a dot-separated string. - getPath: function getPath (obj, ks) { - if (typeof ks == "string") ks = ks.split("."); - - // If we have reached an undefined property - // then stop executing and return undefined - if (obj === undefined) return void 0; - - // If the path array has no more elements, we've reached - // the intended property and return its value - if (ks.length === 0) return obj; - - // If we still have elements in the path array and the current - // value is null, stop executing and return undefined - if (obj === null) return void 0; - - return getPath(obj[_.first(ks)], _.rest(ks)); - }, - - // Returns a boolean indicating whether there is a property - // at the path described by the keys given - hasPath: function hasPath (obj, ks) { - if (typeof ks == "string") ks = ks.split("."); - - var numKeys = ks.length; - - if (obj == null && numKeys > 0) return false; - - if (!(ks[0] in obj)) return false; - - if (numKeys === 1) return true; - - return hasPath(obj[_.first(ks)], _.rest(ks)); - }, - - pickWhen: function(obj, pred) { - var copy = {}; - - _.each(obj, function(value, key) { - if (pred(obj[key])) copy[key] = obj[key]; - }); - - return copy; - }, - - omitWhen: function(obj, pred) { - return _.pickWhen(obj, function(e) { return !pred(e); }); - } - - }); - -})(this); - -// Underscore-contrib (underscore.util.existential.js 0.3.0) -// (c) 2013 Michael Fogus, DocumentCloud and Investigative Reporters & Editors -// Underscore-contrib may be freely distributed under the MIT license. - -(function(root) { - - // Baseline setup - // -------------- - - // Establish the root object, `window` in the browser, or `global` on the server. - var _ = root._ || require('underscore'); - - // Helpers - // ------- - - - // Mixing in the truthiness - // ------------------------ - - _.mixin({ - exists: function(x) { return x != null; }, - truthy: function(x) { return (x !== false) && _.exists(x); }, - falsey: function(x) { return !_.truthy(x); }, - not: function(b) { return !b; }, - firstExisting: function() { - for (var i = 0; i < arguments.length; i++) { - if (arguments[i] != null) return arguments[i]; - } - } - }); - -})(this); - -// Underscore-contrib (underscore.function.arity.js 0.3.0) -// (c) 2013 Michael Fogus, DocumentCloud and Investigative Reporters & Editors -// Underscore-contrib may be freely distributed under the MIT license. - -(function(root) { - - // Baseline setup - // -------------- - - // Establish the root object, `window` in the browser, or `global` on the server. - var _ = root._ || require('underscore'); - - // Setup for variadic operators - // ---------------------------- - - // Turn a binary math operator into a variadic operator - function variadicMath(operator) { - return function() { - return _.reduce(arguments, operator); - }; - } - - // Turn a binary comparator into a variadic comparator - function variadicComparator(comparator) { - return function() { - var result; - for (var i = 0; i < arguments.length - 1; i++) { - result = comparator(arguments[i], arguments[i + 1]); - if (result === false) return result; - } - return result; - }; - } - - // Turn a boolean-returning function into one with the opposite meaning - function invert(fn) { - return function() { - return !fn.apply(this, arguments); - }; - } - - // Basic math operators - function add(x, y) { - return x + y; - } - - function sub(x, y) { - return x - y; - } - - function mul(x, y) { - return x * y; - } - - function div(x, y) { - return x / y; - } - - function mod(x, y) { - return x % y; - } - - function inc(x) { - return ++x; - } - - function dec(x) { - return --x; - } - - function neg(x) { - return -x; - } - - // Bitwise operators - function bitwiseAnd(x, y) { - return x & y; - } - - function bitwiseOr(x, y) { - return x | y; - } - - function bitwiseXor(x, y) { - return x ^ y; - } - - function bitwiseLeft(x, y) { - return x << y; - } - - function bitwiseRight(x, y) { - return x >> y; - } - - function bitwiseZ(x, y) { - return x >>> y; - } - - function bitwiseNot(x) { - return ~x; - } - - // Basic comparators - function eq(x, y) { - return x == y; - } - - function seq(x, y) { - return x === y; - } - - // Not - function not(x) { - return !x; - } - - // Relative comparators - function gt(x, y) { - return x > y; - } - - function lt(x, y) { - return x < y; - } - - function gte(x, y) { - return x >= y; - } - - function lte(x, y) { - return x <= y; - } - - // Mixing in the operator functions - // ----------------------------- - - _.mixin({ - add: variadicMath(add), - sub: variadicMath(sub), - mul: variadicMath(mul), - div: variadicMath(div), - mod: mod, - inc: inc, - dec: dec, - neg: neg, - eq: variadicComparator(eq), - seq: variadicComparator(seq), - neq: invert(variadicComparator(eq)), - sneq: invert(variadicComparator(seq)), - not: not, - gt: variadicComparator(gt), - lt: variadicComparator(lt), - gte: variadicComparator(gte), - lte: variadicComparator(lte), - bitwiseAnd: variadicMath(bitwiseAnd), - bitwiseOr: variadicMath(bitwiseOr), - bitwiseXor: variadicMath(bitwiseXor), - bitwiseNot: bitwiseNot, - bitwiseLeft: variadicMath(bitwiseLeft), - bitwiseRight: variadicMath(bitwiseRight), - bitwiseZ: variadicMath(bitwiseZ) - }); -})(this); - -// Underscore-contrib (underscore.util.strings.js 0.3.0) -// (c) 2013 Michael Fogus, DocumentCloud and Investigative Reporters & Editors -// Underscore-contrib may be freely distributed under the MIT license. - -(function(root) { - - // Baseline setup - // -------------- - - // Establish the root object, `window` in the browser, or `global` on the server. - var _ = root._ || require('underscore'); - - // Helpers - // ------- - - // No reason to create regex more than once - var plusRegex = /\+/g; - var spaceRegex = /\%20/g; - var bracketRegex = /(?:([^\[]+))|(?:\[(.*?)\])/g; - - var urlDecode = function(s) { - return decodeURIComponent(s.replace(plusRegex, '%20')); - }; - var urlEncode = function(s) { - return encodeURIComponent(s).replace(spaceRegex, '+'); - }; - - var buildParams = function(prefix, val, top) { - if (_.isUndefined(top)) top = true; - if (_.isArray(val)) { - return _.map(val, function(value, key) { - return buildParams(top ? key : prefix + '[]', value, false); - }).join('&'); - } else if (_.isObject(val)) { - return _.map(val, function(value, key) { - return buildParams(top ? key : prefix + '[' + key + ']', value, false); - }).join('&'); - } else { - return urlEncode(prefix) + '=' + urlEncode(val); - } - }; - - // Mixing in the string utils - // ---------------------------- - - _.mixin({ - // Explodes a string into an array of chars - explode: function(s) { - return s.split(''); - }, - - // Parses a query string into a hash - fromQuery: function(str) { - var parameters = str.split('&'), - obj = {}, - parameter, - key, - match, - lastKey, - subKey, - depth; - - // Iterate over key/value pairs - _.each(parameters, function(parameter) { - parameter = parameter.split('='); - key = urlDecode(parameter[0]); - lastKey = key; - depth = obj; - - // Reset so we don't have issues when matching the same string - bracketRegex.lastIndex = 0; - - // Attempt to extract nested values - while ((match = bracketRegex.exec(key)) !== null) { - if (!_.isUndefined(match[1])) { - - // If we're at the top nested level, no new object needed - subKey = match[1]; - - } else { - - // If we're at a lower nested level, we need to step down, and make - // sure that there is an object to place the value into - subKey = match[2]; - depth[lastKey] = depth[lastKey] || (subKey ? {} : []); - depth = depth[lastKey]; - } - - // Save the correct key as a hash or an array - lastKey = subKey || _.size(depth); - } - - // Assign value to nested object - depth[lastKey] = urlDecode(parameter[1]); - }); - - return obj; - }, - - // Implodes and array of chars into a string - implode: function(a) { - return a.join(''); - }, - - // Converts a string to camel case - camelCase : function( string ){ - return string.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); }); - }, - - // Converts camel case to dashed (opposite of _.camelCase) - toDash : function( string ){ - string = string.replace(/([A-Z])/g, function($1){return "-"+$1.toLowerCase();}); - // remove first dash - return ( string.charAt( 0 ) == '-' ) ? string.substr(1) : string; - }, - - // Creates a query string from a hash - toQuery: function(obj) { - return buildParams('', obj); - }, - - // Reports whether a string contains a search string. - strContains: function(str, search) { - if (typeof str != 'string') throw new TypeError; - return (str.indexOf(search) != -1); - } - - }); -})(this); - -// Underscore-contrib (underscore.util.trampolines.js 0.3.0) -// (c) 2013 Michael Fogus, DocumentCloud and Investigative Reporters & Editors -// Underscore-contrib may be freely distributed under the MIT license. - -(function(root) { - - // Baseline setup - // -------------- - - // Establish the root object, `window` in the browser, or `global` on the server. - var _ = root._ || require('underscore'); - - // Helpers - // ------- - - - // Mixing in the truthiness - // ------------------------ - - _.mixin({ - done: function(value) { - var ret = _(value); - ret.stopTrampoline = true; - return ret; - }, - - trampoline: function(fun /*, args */) { - var result = fun.apply(fun, _.rest(arguments)); - - while (_.isFunction(result)) { - result = result(); - if ((result instanceof _) && (result.stopTrampoline)) break; - } - - return result.value(); - } - }); - -})(this); diff --git a/dist/underscore-contrib.min.js b/dist/underscore-contrib.min.js deleted file mode 100644 index e8be493..0000000 --- a/dist/underscore-contrib.min.js +++ /dev/null @@ -1,8 +0,0 @@ -// underscore-contrib v0.3.0 -// ========================= - -// > https://github.com/documentcloud/underscore-contrib -// > (c) 2013 Michael Fogus, DocumentCloud and Investigative Reporters & Editors -// > underscore-contrib may be freely distributed under the MIT license. - -(function(n){var r=n._||require("underscore"),t=Array.prototype.slice,e=Array.prototype.concat,u=function(n){return null!=n};r.mixin({cat:function(){return r.reduce(arguments,function(n,u){return r.isArguments(u)?e.call(n,t.call(u)):e.call(n,u)},[])},cons:function(n,t){return r.cat([n],t)},chunk:function(n,t,e){var u=function(n){if(null==n)return[];var i=r.take(n,t);return t===r.size(i)?r.cons(i,u(r.drop(n,t))):e?[r.take(r.cat(i,e),t)]:[]};return u(n)},chunkAll:function(n,t,e){e=null!=e?e:t;var u=function(n,t,e){return r.isEmpty(n)?[]:r.cons(r.take(n,t),u(r.drop(n,e),t,e))};return u(n,t,e)},mapcat:function(n,t){return r.cat.apply(null,r.map(n,t))},interpose:function(n,e){if(!r.isArray(n))throw new TypeError;var u=r.size(n);return 0===u?n:1===u?n:t.call(r.mapcat(n,function(n){return r.cons(n,[e])}),0,-1)},weave:function(){return r.some(arguments)?1==arguments.length?arguments[0]:r.filter(r.flatten(r.zip.apply(null,arguments),!0),function(n){return null!=n}):[]},interleave:r.weave,repeat:function(n,t){return r.times(n,function(){return t})},cycle:function(n,t){return r.flatten(r.times(n,function(){return t}),!0)},splitAt:function(n,t){return[r.take(n,t),r.drop(n,t)]},iterateUntil:function(n,r,t){for(var e=[],u=n(t);r(u);)e.push(u),u=n(u);return e},takeSkipping:function(n,t){var e=[],u=r.size(n);if(0>=t)return[];if(1===t)return n;for(var i=0;u>i;i+=t)e.push(n[i]);return e},reductions:function(n,t,e){var u=[],i=e;return r.each(n,function(r,e){i=t(i,n[e]),u.push(i)}),u},keepIndexed:function(n,t){return r.filter(r.map(r.range(r.size(n)),function(r){return t(r,n[r])}),u)},reverseOrder:function(n){if("string"==typeof n)throw new TypeError("Strings cannot be reversed by _.reverseOrder");return t.call(n).reverse()}})})(this),function(n){var r=n._||require("underscore"),t=Array.prototype.slice,e=Array.prototype.concat,u=function(n){return null!=n},i=function(n){return n!==!1&&u(n)},o=function(n){return r.isArray(n)||r.isArguments(n)};r.mixin({second:function(n,r,e){return null==n?void 0:null==r||e?n[1]:t.call(n,1,r)},third:function(n,r,e){return null==n?void 0:null==r||e?n[2]:t.call(n,2,r)},nth:function(n,r,t){return null==r||t?void 0:n[r]},takeWhile:function(n,t){if(!o(n))throw new TypeError;for(var e=r.size(n),u=0;e>u&&i(t(n[u]));u++);return r.take(n,u)},dropWhile:function(n,t){if(!o(n))throw new TypeError;for(var e=r.size(n),u=0;e>u&&i(t(n[u]));u++);return r.drop(n,u)},splitWith:function(n,t){return[r.takeWhile(n,t),r.dropWhile(n,t)]},partitionBy:function(n,t){if(r.isEmpty(n)||!u(n))return[];var i=r.first(n),o=t(i),c=e.call([i],r.takeWhile(r.rest(n),function(n){return r.isEqual(o,t(n))}));return e.call([c],r.partitionBy(r.drop(n,r.size(c)),t))},best:function(n,t){return r.reduce(n,function(n,r){return t(n,r)?n:r})},keep:function(n,t){if(!o(n))throw new TypeError("expected an array as the first argument");return r.filter(r.map(n,function(n){return t(n)}),u)}})}(this),function(n){function r(n){return u.isElement(n)?n.children:n}function t(n,r,t,e,a,f){var l=[];return function s(n,p,m){if(u.isObject(n)){if(l.indexOf(n)>=0)throw new TypeError(c);l.push(n)}if(t){var v=t.call(a,n,p,m);if(v===o)return o;if(v===i)return}var h,g=r(n);if(u.isObject(g)&&!u.isEmpty(g)){f&&(h=u.isArray(n)?[]:{});var y=u.any(g,function(r,t){var e=s(r,t,n);return e===o?!0:(h&&(h[t]=e),void 0)});if(y)return o}return e?e.call(a,n,p,m,h):void 0}(n)}function e(n,r,t){var e=[];return this.preorder(n,function(n,o){return t||o!=r?(u.has(n,r)&&(e[e.length]=n[r]),void 0):i}),e}var u=n._||require("underscore"),i={},o={},c="Not a tree: same object found in two different branches",a={find:function(n,r,t){var e;return this.preorder(n,function(n,u,i){return r.call(t,n,u,i)?(e=n,o):void 0},t),e},filter:function(n,r,t,e){var u=[];return null==n?u:(r(n,function(n,r,i){t.call(e,n,r,i)&&u.push(n)},null,this._traversalStrategy),u)},reject:function(n,r,t,e){return this.filter(n,r,function(n,r,u){return!t.call(e,n,r,u)})},map:function(n,r,t,e){var u=[];return r(n,function(n,r,i){u[u.length]=t.call(e,n,r,i)},null,this._traversalStrategy),u},pluck:function(n,r){return e.call(this,n,r,!1)},pluckRec:function(n,r){return e.call(this,n,r,!0)},postorder:function(n,r,e,u){u=u||this._traversalStrategy,t(n,u,null,r,e)},preorder:function(n,r,e,u){u=u||this._traversalStrategy,t(n,u,r,null,e)},reduce:function(n,r,e,u){var i=function(n,t,u,i){return r(i||e,n,t,u)};return t(n,this._traversalStrategy,null,i,u,!0)}};a.collect=a.map,a.detect=a.find,a.select=a.filter,u.walk=function(n){var t=u.clone(a);return u.bindAll.apply(null,[t].concat(u.keys(t))),t._traversalStrategy=n||r,t},u.extend(u.walk,u.walk())}(this),function(n){function r(n){return function(){if(1===arguments.length)return n.apply(this,arguments);throw new RangeError("Only a single argument may be accepted.")}}var t=n._||require("underscore"),e=function(){function n(t,e,u,i,o,c){return c===!0?i.unshift(o):i.push(o),i.length==u?t.apply(e,i):r(function(){return n(t,e,u,i.slice(0),arguments[0],c)})}return function(t,e){var u=this;return r(function(){return n(t,u,t.length,[],arguments[0],e)})}}(),u=function(){var n=[];return function(r){if("function"!=typeof r)throw Error("Argument 1 must be a function.");var t=r.length;return void 0===n[t]&&(n[t]=function(n){return function(){if(arguments.length!==t)throw new RangeError(t+" arguments must be applied.");return n.apply(this,arguments)}}),n[t](r)}}();t.mixin({fix:function(n){var r=t.rest(arguments),e=function(){for(var e=r.slice(),u=0,i=0;(e.length||arguments.length>u)>i;i++)e[i]===t&&(e[i]=arguments[u++]);return n.apply(null,e)};return e._original=n,e},unary:function(n){return function(r){return n.call(this,r)}},binary:function(n){return function(r,t){return n.call(this,r,t)}},ternary:function(n){return function(r,t,e){return n.call(this,r,t,e)}},quaternary:function(n){return function(r,t,e,u){return n.call(this,r,t,e,u)}},curry:e,rCurry:function(n){return e.call(this,n,!0)},curry2:function(n){return r(function(t){return r(function(r){return n.call(this,t,r)})})},curry3:function(n){return r(function(t){return r(function(e){return r(function(r){return n.call(this,t,e,r)})})})},rcurry2:function(n){return r(function(t){return r(function(r){return n.call(this,r,t)})})},rcurry3:function(n){return r(function(t){return r(function(e){return r(function(r){return n.call(this,r,e,t)})})})},enforce:u}),t.arity=function(){var n={};return function r(t,e){if(null==n[t]){for(var u=Array(t),i=0;t>i;++i)u[i]="__"+i;var o=u.join(),c="return function ("+o+") { return fun.apply(this, arguments); };";n[t]=Function(["fun"],c)}return null==e?function(n){return r(t,n)}:n[t](e)}}()}(this),function(n){function r(n,r){return t.arity(n.length,function(){return n.apply(this,c.call(arguments,r))})}var t=n._||require("underscore"),e=function(n){return null!=n},u=function(n){return n!==!1&&e(n)},i=[].reverse,o=[].slice,c=[].map,a=function(n){return function(r,t){return 1===arguments.length?function(t){return n(r,t)}:n(r,t)}};t.mixin({always:t.constant,pipeline:function(){var n=t.isArray(arguments[0])?arguments[0]:arguments;return function(r){return t.reduce(n,function(n,r){return r(n)},r)}},conjoin:function(){var n=arguments;return function(r){return t.every(r,function(r){return t.every(n,function(n){return n(r)})})}},disjoin:function(){var n=arguments;return function(r){return t.some(r,function(r){return t.some(n,function(n){return n(r)})})}},comparator:function(n){return function(r,t){return u(n(r,t))?-1:u(n(t,r))?1:0}},complement:function(n){return function(){return!n.apply(this,arguments)}},splat:function(n){return function(r){return n.apply(this,r)}},unsplat:function(n){var r=n.length;return 1>r?n:1===r?function(){return n.call(this,o.call(arguments,0))}:function(){var t=arguments.length,e=o.call(arguments,0,r-1),u=Math.max(r-t-1,0),i=Array(u),c=o.call(arguments,n.length-1);return n.apply(this,e.concat(i).concat([c]))}},unsplatl:function(n){var r=n.length;return 1>r?n:1===r?function(){return n.call(this,o.call(arguments,0))}:function(){var t=arguments.length,e=o.call(arguments,Math.max(t-r+1,0)),u=o.call(arguments,0,Math.max(t-r+1,0));return n.apply(this,[u].concat(e))}},mapArgs:a(r),juxt:function(){var n=arguments;return function(){var r=arguments;return t.map(n,function(n){return n.apply(this,r)},this)}},fnull:function(n){var r=t.rest(arguments);return function(){for(var u=t.toArray(arguments),i=t.size(r),o=0;i>o;o++)e(u[o])||(u[o]=r[o]);return n.apply(this,u)}},flip2:function(n){return function(){var r=o.call(arguments);return r[0]=arguments[1],r[1]=arguments[0],n.apply(this,r)}},flip:function(n){return function(){var r=i.call(arguments);return n.apply(this,r)}},functionalize:function(n){return function(r){return n.apply(r,t.rest(arguments))}},methodize:function(n){return function(){return n.apply(null,t.cons(this,arguments))}},k:t.always,t:t.pipeline}),t.unsplatr=t.unsplat,t.mapArgsWith=a(t.flip(r)),t.bound=function(n,r){var e=n[r];if(!t.isFunction(e))throw new TypeError("Expected property to be a function");return t.bind(e,n)}}(this),function(n){var r=n._||require("underscore"),t=Array.prototype.slice;r.mixin({attempt:function(n,e){if(null==n)return void 0;var u=n[e],i=t.call(arguments,2);return r.isFunction(u)?u.apply(n,i):void 0}})}(this),function(n){function r(n){return function(r){return n.call(this,r)}}function t(n,r,t){var e,u;for(e=t!==void 0?t:n(),u=n();null!=u;)e=r.call(u,e,u),u=n();return e}function e(n,r){var t=x;return function(){return t===x?t=n:null!=t&&(t=r.call(t,t)),t}}function u(n,r){var t,e,u=n;return function(){return null!=u?(t=r.call(u,u),e=t[1],u=null!=e?t[0]:void 0,e):void 0}}function i(n,r,t){var e=t;return function(){var t=n();return null==t?t:e=e===void 0?t:r.call(t,e,t)}}function o(n,r,t){var e,u,i=t;return function(){return u=n(),null==u?u:i===void 0?i=u:(e=r.call(u,i,u),i=e[0],e[1])}}function c(n,r){return function(){var t;return t=n(),null!=t?r.call(t,t):void 0}}function a(n,r){var t=null;return function(){var e,u;if(null==t){if(u=n(),null==u)return t=null,void 0;t=r.call(u,u)}for(;null==e;)if(e=t(),null==e){if(u=n(),null==u)return t=null,void 0;t=r.call(u,u)}return e}}function f(n,r){return function(){var t;for(t=n();null!=t;){if(r.call(t,t))return t;t=n()}return void 0}}function l(n,r){return f(n,function(n){return!r(n)})}function s(n,r){return f(n,r)()}function p(n,r,t){for(var e=0;r-->0;)n();return null!=t?function(){return t>=++e?n():void 0}:n}function m(n,r){return p(n,null==r?1:r)}function v(n,r){return p(n,0,null==r?1:r)}function h(n){var r=0;return function(){return n[r++]}}function g(n){var r,t,e;return r=0,e=[],t=function(){var u,i;return u=n[r++],u instanceof Array?(e.push({array:n,index:r}),n=u,r=0,t()):u===void 0?e.length>0?(i=e.pop(),n=i.array,r=i.index,t()):void 0:u}}function y(n){return function(){return n}}function d(n,r,t){return function(){var e;return n>r?void 0:(e=n,n+=t,e)}}function w(n,r,t){return function(){var e;return r>n?void 0:(e=n,n-=t,e)}}function A(n,r,t){return null==n?d(1,1/0,1):null==r?d(n,1/0,1):null==t?r>=n?d(n,r,1):w(n,r,1):t>0?d(n,r,t):0>t?w(n,r,Math.abs(t)):k(n)}var b=n._||require("underscore"),x={},_=r(A);b.iterators={accumulate:i,accumulateWithReturn:o,foldl:t,reduce:t,unfold:e,unfoldWithReturn:u,map:c,mapcat:a,select:f,reject:l,filter:f,find:s,slice:p,drop:m,take:v,List:h,Tree:g,constant:y,K:y,numbers:_,range:A}}(this,void 0),function(n){var r=n._||require("underscore");r.mixin({isInstanceOf:function(n,r){return n instanceof r},isAssociative:function(n){return r.isArray(n)||r.isObject(n)||r.isArguments(n)},isIndexed:function(n){return r.isArray(n)||r.isString(n)||r.isArguments(n)},isSequential:function(n){return r.isArray(n)||r.isArguments(n)},isPlainObject:function(t){return r.isObject(t)&&t.constructor===n.Object},isZero:function(n){return 0===n},isEven:function(n){return r.isFinite(n)&&0===(1&n)},isOdd:function(n){return r.isFinite(n)&&!r.isEven(n)},isPositive:function(n){return n>0},isNegative:function(n){return 0>n},isValidDate:function(n){return r.isDate(n)&&!r.isNaN(n.getTime())},isNumeric:function(n){return!isNaN(parseFloat(n))&&isFinite(n)},isInteger:function(n){return r.isNumeric(n)&&0===n%1},isFloat:function(n){return r.isNumeric(n)&&!r.isInteger(n)},isJSON:function(n){try{JSON.parse(n)}catch(r){return!1}return!0},isIncreasing:function(){var n=r.size(arguments);if(1===n)return!0;if(2===n)return arguments[0]t;t++)if(arguments[t-1]>=arguments[t])return!1;return!0},isDecreasing:function(){var n=r.size(arguments);if(1===n)return!0;if(2===n)return arguments[0]>arguments[1];for(var t=1;n>t;t++)if(arguments[t-1]<=arguments[t])return!1;return!0}})}(this),function(n){var r=n._||require("underscore"),t=(Array.prototype.slice,Array.prototype.concat),e=function(n){return null!=n},u=function(n){return n!==!1&&e(n)},i=function(n){return r.isArray(n)||r.isObject(n)},o=function(n){return function(r){return function(t){return n(t,r)}}};r.mixin({merge:function(){var n=r.some(arguments)?{}:null;return u(n)&&r.extend.apply(null,t.call([n],r.toArray(arguments))),n},renameKeys:function(n,u){return r.reduce(u,function(r,t,u){return e(n[u])?(r[t]=n[u],r):r},r.omit.apply(null,t.call([n],r.keys(u))))},snapshot:function(n){if(null==n||"object"!=typeof n)return n;var t=new n.constructor;for(var e in n)n.hasOwnProperty(e)&&(t[e]=r.snapshot(n[e]));return t},updatePath:function(n,t,u,o){if(!i(n))throw new TypeError("Attempted to update a non-associative object.");if(!e(u))return t(n);var c=r.isArray(u),a=c?u:[u],f=c?r.snapshot(n):r.clone(n),l=r.last(a),s=f;return r.each(r.initial(a),function(n){o&&!r.has(s,n)&&(s[n]=r.clone(o)),s=s[n]}),s[l]=t(s[l]),f},setPath:function(n,t,u,i){if(!e(u))throw new TypeError("Attempted to set a property at a null path.");return r.updatePath(n,function(){return t},u,i)},frequencies:o(r.countBy)(r.identity)})}(this),function(n){var r=n._||require("underscore"),t=Array.prototype.concat,e=Array.prototype;e.slice,r.mixin({accessor:function(n){return function(r){return r&&r[n]}},dictionary:function(n){return function(r){return n&&r&&n[r]}},selectKeys:function(n,e){return r.pick.apply(null,t.call([n],e))},kv:function(n,t){return r.has(n,t)?[t,n[t]]:void 0},getPath:function u(n,t){return"string"==typeof t&&(t=t.split(".")),void 0===n?void 0:0===t.length?n:null===n?void 0:u(n[r.first(t)],r.rest(t))},hasPath:function i(n,t){"string"==typeof t&&(t=t.split("."));var e=t.length;return null==n&&e>0?!1:t[0]in n?1===e?!0:i(n[r.first(t)],r.rest(t)):!1},pickWhen:function(n,t){var e={};return r.each(n,function(r,u){t(n[u])&&(e[u]=n[u])}),e},omitWhen:function(n,t){return r.pickWhen(n,function(n){return!t(n)})}})}(this),function(n){var r=n._||require("underscore");r.mixin({exists:function(n){return null!=n},truthy:function(n){return n!==!1&&r.exists(n)},falsey:function(n){return!r.truthy(n)},not:function(n){return!n},firstExisting:function(){for(var n=0;arguments.length>n;n++)if(null!=arguments[n])return arguments[n]}})}(this),function(n){function r(n){return function(){return E.reduce(arguments,n)}}function t(n){return function(){for(var r,t=0;arguments.length-1>t;t++)if(r=n(arguments[t],arguments[t+1]),r===!1)return r;return r}}function e(n){return function(){return!n.apply(this,arguments)}}function u(n,r){return n+r}function i(n,r){return n-r}function o(n,r){return n*r}function c(n,r){return n/r}function a(n,r){return n%r}function f(n){return++n}function l(n){return--n}function s(n){return-n}function p(n,r){return n&r}function m(n,r){return n|r}function v(n,r){return n^r}function h(n,r){return n<>r}function y(n,r){return n>>>r}function d(n){return~n}function w(n,r){return n==r}function A(n,r){return n===r}function b(n){return!n}function x(n,r){return n>r}function k(n,r){return r>n}function _(n,r){return n>=r}function q(n,r){return r>=n}var E=n._||require("underscore");E.mixin({add:r(u),sub:r(i),mul:r(o),div:r(c),mod:a,inc:f,dec:l,neg:s,eq:t(w),seq:t(A),neq:e(t(w)),sneq:e(t(A)),not:b,gt:t(x),lt:t(k),gte:t(_),lte:t(q),bitwiseAnd:r(p),bitwiseOr:r(m),bitwiseXor:r(v),bitwiseNot:d,bitwiseLeft:r(h),bitwiseRight:r(g),bitwiseZ:r(y)})}(this),function(n){var r=n._||require("underscore"),t=/\+/g,e=/\%20/g,u=/(?:([^\[]+))|(?:\[(.*?)\])/g,i=function(n){return decodeURIComponent(n.replace(t,"%20"))},o=function(n){return encodeURIComponent(n).replace(e,"+")},c=function(n,t,e){return r.isUndefined(e)&&(e=!0),r.isArray(t)?r.map(t,function(r,t){return c(e?t:n+"[]",r,!1)}).join("&"):r.isObject(t)?r.map(t,function(r,t){return c(e?t:n+"["+t+"]",r,!1)}).join("&"):o(n)+"="+o(t)};r.mixin({explode:function(n){return n.split("")},fromQuery:function(n){var t,e,o,c,a,f=n.split("&"),l={};return r.each(f,function(n){for(n=n.split("="),t=i(n[0]),o=t,a=l,u.lastIndex=0;null!==(e=u.exec(t));)r.isUndefined(e[1])?(c=e[2],a[o]=a[o]||(c?{}:[]),a=a[o]):c=e[1],o=c||r.size(a);a[o]=i(n[1])}),l},implode:function(n){return n.join("")},camelCase:function(n){return n.replace(/-([a-z])/g,function(n){return n[1].toUpperCase()})},toDash:function(n){return n=n.replace(/([A-Z])/g,function(n){return"-"+n.toLowerCase()}),"-"==n.charAt(0)?n.substr(1):n},toQuery:function(n){return c("",n)},strContains:function(n,r){if("string"!=typeof n)throw new TypeError;return-1!=n.indexOf(r)}})}(this),function(n){var r=n._||require("underscore");r.mixin({done:function(n){var t=r(n);return t.stopTrampoline=!0,t},trampoline:function(n){for(var t=n.apply(n,r.rest(arguments));r.isFunction(t)&&(t=t(),!(t instanceof r&&t.stopTrampoline)););return t.value()}})}(this); \ No newline at end of file diff --git a/docs/underscore.array.builders.js.md b/docs/underscore.array.builders.js.md index 0467e85..d5850b7 100644 --- a/docs/underscore.array.builders.js.md +++ b/docs/underscore.array.builders.js.md @@ -93,7 +93,7 @@ _.chunkAll([0,1,2,3,4], 3); Also, `_.chunkAll` takes an optional third argument signifying that paritions should be built from skipped regions: ```javascript -_.chunkAll(_.range(1), 2, 4); +_.chunkAll(_.range(10), 2, 4); //=> [[0,1],[4,5],[8,9]] ``` @@ -338,4 +338,4 @@ _.weave(['a','b','c'], [1]); The `_.interleave` function is an alias for `_.weave`. --------------------------------------------------------------------------------- \ No newline at end of file +-------------------------------------------------------------------------------- diff --git a/docs/underscore.collections.walk.js.md b/docs/underscore.collections.walk.js.md index 5c6b7c4..a231f23 100644 --- a/docs/underscore.collections.walk.js.md +++ b/docs/underscore.collections.walk.js.md @@ -11,5 +11,6 @@ Documentation should use [Journo](https://github.com/jashkenas/journo) formats a map: function(obj, strategy, visitor, context) pluck: function(obj, propertyName) pluckRec: function(obj, propertyName) + containsAtLeast: function(list, count, value) + containsAtMost: function(list, count, value) _.walk.collect = _.walk.map; - diff --git a/docs/underscore.object.builders.js.md b/docs/underscore.object.builders.js.md index 74e27c2..2314be6 100644 --- a/docs/underscore.object.builders.js.md +++ b/docs/underscore.object.builders.js.md @@ -26,7 +26,7 @@ _.frequencies(citations); Returns a new object resulting from merging the passed objects. Objects are processed in order, so each will override properties of the same -name occurring in earlier arguments. +name occurring in earlier arguments. Returns `null` if called without arguments. @@ -148,3 +148,27 @@ obj === imperialObj; ``` -------------------------------------------------------------------------------- + +#### omitPath + +**Signature:** `_.omitPath(obj:Object, ks:String|Array)` + +Returns a copy of `obj` excluding the value represented by the `ks` path. +Path may be given as an array or as a dot-separated string. + +```javascript +var test = { + foo: true, + bar: false, + baz: 42, + dada: { + carlos: { + pepe: 9 + }, + pedro: 'pedro' + } +}; + +_.omitPath(test, 'dada.carlos.pepe'); +// => {foo: true, bar: false, baz: 42, dada: {carlos: {}, pedro: 'pedro'}} +``` diff --git a/docs/underscore.util.trampolines.js.md b/docs/underscore.util.trampolines.js.md index 2de8c9a..4e2505b 100644 --- a/docs/underscore.util.trampolines.js.md +++ b/docs/underscore.util.trampolines.js.md @@ -29,7 +29,7 @@ a naive recursive function, use `_.partial` as illustrated below. function isEvenNaive (num) { if (num === 0) return true; if (num === 1) return false; - return isEvenNaive(num - 2); + return isEvenNaive(Math.abs(num) - 2); } isEvenNaive(99999); @@ -50,4 +50,4 @@ isEven(99999); // => false ``` --------------------------------------------------------------------------------- \ No newline at end of file +-------------------------------------------------------------------------------- diff --git a/index.html b/index.html deleted file mode 100644 index 4177872..0000000 --- a/index.html +++ /dev/null @@ -1,2135 +0,0 @@ - - - - - - - - - - - - - -

Underscore-contrib (0.3.0)

-
-

The brass buckles on Underscore's utility belt - a contributors' library for Underscore.

-
-

Introduction

-

Places

- -

Why underscore-contrib?

-

While Underscore provides a bevy of useful tools to support functional programming in JavaScript, it can't -(and shouldn't) be everything to everyone. Underscore-contrib is intended as a home for functions that, for -various reasons, don't belong in Underscore proper. In particular, it aims to be:

- -

Use

-

In the Browser

-

First, you'll need Underscore version 1.6.0 or higher. Then you can grab the relevant underscore-contrib sub-libraries and simply add something like -the following to your pages:

-
<script type="text/javascript" src="underscore.js"></script>
-<script type="text/javascript" src="underscore.object.builders.js"></script>
-

At the moment there are no cross-contrib dependencies (i.e. each sub-library -can stand by itself), but that may change in the future.

-

In Node.js

-

Using contrib in Node is very simple. Just install it with npm:

-
npm install underscore-contrib --save
-

Then require it within your project like so:

-
var _ = require('underscore-contrib');
-

The _ variable will be a copy of Underscore with contrib's methods already -mixed in.

-

License

-

_.contrib is open sourced under the MIT license.

-

Sub-libraries

-

The _.contrib library currently contains a number of related capabilities, aggregated into the following files.

- -

The links above are to the annotated source code. Full-blown _.contrib documentation is in the works. Contributors welcomed.

-

array.builders

-
-

Functions to build arrays. View Annotated Source

-
-
-

cat

-

Signature: _.cat(... arrays:Array ...)

-

The _.cat function provides a way to concatenate zero or more heterogeneous arrays into one.

-
_.cat();                    // 0-args
-//=> []
-
-_.cat([]);                  // 1-arg, empty array
-//=> []
-
-_.cat([1,2,3]);             // 1-arg
-//=> [1,2,3]
-
-_.cat([1,2,3],[4,5,6]);     // 2-args
-//=> [1,2,3,4,5,6]
-
-_.cat([1,2,3],[4,5,6],[7]); // 3+ args
-//=> [1,2,3,4,5,6,7]
-

Not every argument to _.cat needs to be an array; other types are accepted.

-

Signature: _.cat(... elems:Any ...)

-
_.cat(1,[2],3,4);           // mixed args
-//=> [1,2,3,4]
-

The _.cat function will also work with the arguments object as if it were an array.

-

Signature: _.cat(... elems:Arguments ...)

-
function f(){ return _.cat(arguments, 4,5,6); }
-
-f(1,2,3);
-//=> [1,2,3,4,5,6]
-
-

chunk

-

The _.chunk function, by default, accepts an array and a number and splits and returns a new array representing the original array split into some number of arrays of the given size:

-
_.chunk([0,1,2,3], 2);
-//=> , [[0,1],[2,3]]
-

If the original array cannot completely fulfill the chunk scheme then the array returned will drop the undersized final chunk:

-
_.chunk([0,1,2,3,4], 2);
-//=> , [[0,1],[2,3]]
-

You can pass an optional third argument to _.chunk to pad out the final array chunk should it fall short. If the value given as the third argument is not an array then it is repeated the needed number of times:

-
_.chunk([0,1,2,3,4], 3, '_');
-//=> , [[0,1,2],[3,'_','_']]
-

If you given an array as the optional third argument then that array is used to pad in-place as needed:

-
_.chunk([0,1,2,3,4], 3, ['a', 'b']);
-//=> , [[0,1,2],[3,'a','b']]
-
-

chunkAll

-

The _.chunkAll function is similar to _.chunk except for the following. First, _.chunkAll will never drop short chunks from the end:

-
_.chunkAll([0,1,2,3,4], 3);
-//=> , [[0,1,2],[3]]
-

Also, _.chunkAll takes an optional third argument signifying that paritions should be built from skipped regions:

-
_.chunkAll(_.range(1), 2, 4);
-//=> [[0,1],[4,5],[8,9]]
-
-

cons

-

Signature: _.cons(head:Any, tail:Array)

-

The _.cons function provides a way to "construct" a new array by taking some element and putting it at the front of another array.

-
_.cons(0, []);
-//=> [0]
-
-_.cons(1, [2]);
-//=> [1,2]
-
-_.cons([0], [1,2,3]);
-//=> [0,1,2,3]
-

The _.cons function also can be used to create pairs if the second argument is not an array.

-

Signature: _.cons(head:Any, tail:Any)

-
_.cons(1, 2);
-//=> [1,2]
-
-_.cons([1], 2);
-//=> [[1],2]
-

Finally, _.cons will operate with the arguments object.

-

Signature: _.cons(head:Any, tail:Arguments)

-
function f() { return _.cons(0, arguments) }
-
-f(1,2,3);
-//=> [0,1,2,3]
-
-

cycle

-

The _.cycle function takes an integer value used to build an array of that size containing the number of iterations through the given array, strung end-to-end as many times as needed. An example is probably more instructive:

-
_.cycle(5, [1,2,3]);
-//=> [1,2,3,1,2]
-
-

interpose

-

The _.interpose function takes an array and an element and returns a new array with the given element inserted betwixt every element in the original array:

-
_.interpose([1,2,3], 0);
-//=> [1,0,2,0,3]
-

If there are no betweens (i.e. empty and single-element arrays), then the original array is returned:

-
_.interpose([1], 0);
-//=> [1]
-
-_.interpose([], 0);
-//=> []
-
-

iterateUntil

-

The _.iterateUntil function takes a function used as a result generator, a function used as a stop-check and a seed value and returns an array of each generated result. The operation of _.iterateUntil is such that the result generator is passed the seed to start and each subsequent result which will continue until a result fails the check function (i.e. returns falsey). An example is best:

-
var dec = function(n) { return n - 1; };
-var isPos = function(n) { return n > 0; };
-

The dec result generator takes a number and decrements it by one. The isPos predicate takes a number and returns true if it's positive. Using these two functions you can build an array of every number from 6 to 0, inclusive:

-
_.iterateUntil(dec, isPos, 6);
-//=> [5,4,3,2,1]
-

That is, the array only contains every number from 5 down to 1 because when the result of dec got to 0 the isPos check failed (i.e. went falsey) thus terminating the execution.

-
-

keepIndexed

-

The _.keepIndexed function takes an array and a function and returns a new array filled with the non-null return results of the given function on the elements or keys in the given array:

-
_.keepIndexed([1,2,3], function(k) { 
-  return i === 1 || i === 2;
-});
-
-//=> [false, true, true]
-

If you return either null or undefined then the result is dropped from the resulting array:

-
_.keepIndexed(['a','b','c'], function(k, v) { 
-  if (k === 1) return v; 
-});
-
-//=> ['b']
-
-

mapcat

-

There are times when a mapping operation produces results contained in arrays, but the final result should be flattened one level. For these circumstances you can use _.mapcat to produce results:

-
var array = [1,2,null,4,undefined,6];
-
-var errors = _.mapcat(array, function(e,i) {
-  if (e == null) {
-    return ["Element @" + i + " is bad"];
-  }
-  else {
-    return [];
-  }
-});
-

Inspecting the contents of errors shows:

-
["Element @2 is bad", "Element @4 is bad"]
-

The _.mapcat function is equivalent to _.cat.apply(array, _.map(array,fun)).

-
-

reductions

-

The _.reductions function is similar to Underscore's builtin _.reduce function except that it returns an array of every intermediate value in the folding operation:

-
_.reductions([1,2,3,4,5], function(agg, n) {
-  return agg + n;
-}, 0);
-
-//=> [1,3,6,10,15]
-

The last element in the array returned from _.reductions is the answer that you would get if you had just chosen to use _.reduce.

-
-

repeat

-

Signature: _.repeat(t:Integer, value:Any)

-

The _.repeat function takes an integer value used to build an array of that size containing the value given:

-
_.repeat(5, 'a');
-//=> ['a','a','a','a','a']
-
-

splitAt

-

The _.splitAt function takes an array and a numeric index and returns a new array with two embedded arrays representing a split of the original array at the index provided:

-
_.splitAt([1,2,3,4,5], 2);
-//=> [[1,2],[3,4,5]]
-
-_.splitAt([1,2,3,4,5], 0);
-//=> [[],[1,2,3,4,5]]
-

The operation of _.splitAt is safe if the index provided is outside the range of legal indices:

-
_.splitAt([1,2,3,4,5], 20000);
-//=> [[1,2,3,4,5],[]]
-
-_.splitAt([1,2,3,4,5], -1000);
-//=> [[],[1,2,3,4,5]]    
-
-_.splitAt([], 0);
-//=> [[],[]]
-
-

takeSkipping

-

The _.takeSkipping function takes an array and a number and returns a new array containing every nth element in the original array:

-
_.takeSkipping(_.range(10), 2);
-//=> [0,2,4,6,8]
-

The _.takeSkipping function is safe against numbers larger or smaller than the array size:

-
_.takeSkipping(_.range(10), 100000);
-//=> [0]
-
-_.takeSkipping(_.range(10), -100);
-//=> []
-
-

weave

-

The _.weave function works similarly to _.interpose (shown above) except that it accepts an array used as the interposition values. In other words, _.weave takes two arrays and returns a new array with the original elements woven together. An example would help:

-
_.weave(['a','b','c'], [1,2,3]);
-//=> ['a',1,'b',2,'c',3]
-

The array returned from _.weave will be as long as the longest array given with the woven entries stopping according to the shortest array:

-
_.weave(['a','b','c'], [1]);
-//=> ['a',1,'b','c']
-

The _.interleave function is an alias for _.weave.

-
-

array.selectors

-
-

Functions to take things from arrays. View Annotated Source

-
-
-

best

-

Signature: _.best(array:Array, fun:Function)

-

Returns the "best" value in an array based on the result of a given function.

-
_.best([1, 2, 3, 4, 5], function(x, y) {
-  return x > y;
-});
-//=> 5
-
-

dropWhile

-

Signature: _.dropWhile(array:Array, pred:Function)

-

Drops elements for which the given function returns a truthy value.

-
_.dropWhile([-2,-1,0,1,2], isNeg);
-//=> [0,1,2]
-
-

keep

-

Signature: _.keep(array:Array, fun:Function)

-

Returns an array of existy results of a function over a source array.

-
_.keep([1, 2, 3, 4, 5], function(val) {
-  if (val % 3 === 0) {
-    return val;
-  }
-});
-// => [3]
-
-

nth

-

Signature: _.nth(array:Array, index:Number[, guard:Any])

-

The _.nth function is a convenience for the equivalent array[n]. The -optional guard value allows _.nth to work correctly as a callback for -_.map.

-
_.nth(['a','b','c'], 2);
-//=> 'c'
-

If given an index out of bounds then _.nth will return undefined:

-
_.nth(['a','b','c'], 2000);
-//=> undefined
-

The _.nth function can also be used in conjunction with _.map and _.compact like so:

-
var b = [['a'],['b'],[]];
-
-_.compact(_.map(b, function(e) { return _.nth(e,0) }));
-//=> ['a','b']
-

If wrapping a function around _.nth is too tedious or you'd like to partially apply the index then Underscore-contrib offers any of _.flip2, _.fix or _.curryRight2 to solve this.

-
-

partitionBy

-

Signature: _.keep(array:Array, fun:Function)

-

Takes an array and partitions it into sub-arrays as the given predicate changes -truth sense.

-
_.partitionBy([1,2,2,3,1,1,5], _.isEven);
-// => [[1],[2,2],[3,1,1,5]]
-
-_.partitionBy([1,2,2,3,1,1,5], _.identity);
-// => [[1],[2,2],[3],[1,1],[5]]
-
-

second

-

Signature: _.second(array:Array, index:Number[, guard:Any])

-

The _.second function is a convenience for the equivalent array[1]. The -optional guard value allows _.second to work correctly as a callback for -_.map.

-
_.second(['a','b']);
-//=> 'b'
-
-_.map([['a','b'], _.range(10,20)], _.second);
-//=> ['b',11]
-

You can also pass an optional number to the _.second function to take a number of elements from an array starting with the second element and ending at the given index:

-
_.second(_.range(10), 5)
-//=> [1, 2, 3, 4]
-
-

takeWhile

-

Signature: _.takeWhile(array:Array, pred:Function)

-

The _.takeWhile function takes an array and a function and returns a new array containing the first n elements in the original array for which the given function returns a truthy value:

-
var isNeg = function(n) { return n < 0; };
-
-_.takeWhile([-2,-1,0,1,2], isNeg);
-//=> [-2,-1]
-
-

third

-

Signature: _.third(array:Array, index:Number[, guard:Any])

-

The _.third function is a convenience for the equivalent array[2]. The -optional guard value allows _.third to work correctly as a callback for -_.map.

-
_.third(['a','b','c']);
-//=> 'c'
-
-_.map([['a','b','c'], _.range(10,20)], _.third);
-//=> ['c',12]
-

You can also pass an optional number to the _.third function to take a number of elements from an array starting with the third element and ending at the given index:

-
_.third(_.range(10), 5)
-//=> [2, 3, 4]
-
-

collections.walk

-
-

Functions to recursively walk collections which are trees.

-
-

Documentation should use Journo formats and standards.

-
  _.walk = walk;
-  postorder: function(obj, visitor, context)
-  preorder: function(obj, visitor, context)
-  walk(obj, visitor, null, context)
-  map: function(obj, strategy, visitor, context)
-  pluck: function(obj, propertyName)
-  pluckRec: function(obj, propertyName)
-  _.walk.collect = _.walk.map;
-

function.arity

-
-

Functions which manipulate the way functions work with their arguments.

-
-
-

arity

-

Signature: _.arity(numberOfArgs:Number, fun:Function)

-

Returns a new function which is equivalent to fun, except that the new -function's length property is equal to numberOfArgs. This does not limit -the function to using that number of arguments. It's only effect is on the -reported length.

-
function addAll() {
-     var sum = 0;
-     for (var i = 0; i < arguments.length; i++) {
-         sum = sum + arguments[i];
-     }
-     return sum;
-}
-
-addAll.length
-// => 0
-
-var addAllWithFixedLength = _.arity(2, addAll);
-
-addAllWithFixedLength.length
-// => 2
-
-addAllWithFixedLength(1, 1, 1, 1);
-// => 4
-
-

binary

-

Signature: _.binary(fun:Function)

-

Returns a new function which accepts only two arguments and passes these -arguments to fun. Additional arguments are discarded.

-
function addAll() {
-     var sum = 0;
-     for (var i = 0; i < arguments.length; i++) {
-         sum = sum + arguments[i];
-     }
-     return sum;
-}
-
-var add2 = _.binary(addAll);
-
-add2(1, 1);
-// => 2
-
-add2(1, 1, 1, 1);
-// => 2
-
-

curry

-

Signature: _.curry(func:Function[, reverse:Boolean])

-

Returns a curried version of func. If reverse is true, arguments will be -processed from right to left.

-
function add3 (x, y, z) {
-    return x + y + z;
-}
-
-var curried = _.curry(add3);
-// => function
-
-curried(1);
-// => function
-
-curried(1)(2);
-// => function
-
-curried(1)(2)(3);
-// => 6
-
-

curry2

-

Signature: _.curry2(fun:Function)

-

Returns a curried version of func, but will curry exactly two arguments, no -more or less.

-
function add2 (a, b) {
-    return a + b;
-}
-
-var curried = _.curry2(add2);
-// => function
-
-curried(1);
-// => function
-
-curried(1)(2);
-// => 3
-
-

curry3

-

Signature: _.curry3(fun:Function)

-

Returns a curried version of func, but will curry exactly three arguments, no -more or less.

-
function add3 (a, b, c) {
-    return a + b + c;
-}
-
-var curried = _.curry3(add3);
-// => function
-
-curried(1);
-// => function
-
-curried(1)(2);
-// => function
-
-curried(1)(2)(3);
-// => 6
-
-

curryRight

-

Signature: _.curryRight(func:Function)

-

Aliases: _.rCurry

-

Returns a curried version of func where arguments are processed from right -to left.

-
function divide (a, b) {
-    return a / b;
-}
-
-var curried = _.curryRight(divide);
-// => function
-
-curried(1);
-// => function
-
-curried(1)(2);
-// => 2
-
-curried(2)(1);
-// => 0.5
-
-

curryRight2

-

Signature: _.curryRight2(func:Function)

-

Aliases: _.rcurry2

-

Returns a curried version of func where a maxium of two arguments are -processed from right to left.

-
function concat () {
-    var str = "";
-
-    for (var i = 0; i < arguments.length; i++) {
-        str = str + arguments[i];
-    }
-
-    return str;
-}
-
-var curried = _.curryRight2(concat);
-// => function
-
-curried("a");
-// => function
-
-curried("a")("b");
-// => "ba"
-
-

curryRight3

-

Signature: _.curryRight3(func:Function)

-

Aliases: _.rcurry3

-

Returns a curried version of func where a maxium of three arguments are -processed from right to left.

-
function concat () {
-    var str = "";
-
-    for (var i = 0; i < arguments.length; i++) {
-        str = str + arguments[i];
-    }
-
-    return str;
-}
-
-var curried = _.curryRight3(concat);
-// => function
-
-curried("a");
-// => function
-
-curried("a")("b");
-// => function
-
-curried("a")("b")("c");
-// => "cba"
-
-

fix

-

Signature: _.fix(fun:Function[, value:Any...])

-

Fixes the arguments to a function based on the parameter template defined by -the presence of values and the _ placeholder.

-
function add3 (a, b, c) {
-    return a + b + c;
-}
-
-var fixedFirstAndLast = _.fix(add3, 1, _, 3);
-// => function
-
-fixedFirstAndLast(2);
-// => 6
-
-fixedFirstAndLast(10);
-// => 14
-
-

quaternary

-

Signature: _.quaternary(fun:Function)

-

Returns a new function which accepts only four arguments and passes these -arguments to fun. Additional arguments are discarded.

-
function addAll() {
-     var sum = 0;
-     for (var i = 0; i < arguments.length; i++) {
-         sum = sum + arguments[i];
-     }
-     return sum;
-}
-
-var add4 = _.quaternary(addAll);
-
-add4(1, 1, 1, 1);
-// => 4
-
-add4(1, 1, 1, 1, 1, 1);
-// => 4
-
-

ternary

-

Signature: _.ternary(fun:Function)

-

Returns a new function which accepts only three arguments and passes these -arguments to fun. Additional arguments are discarded.

-
function addAll() {
-     var sum = 0;
-     for (var i = 0; i < arguments.length; i++) {
-         sum = sum + arguments[i];
-     }
-     return sum;
-}
-
-var add3 = _.ternary(addAll);
-
-add3(1, 1, 1);
-// => 3
-
-add3(1, 1, 1, 1, 1, 1);
-// => 3
-
-

unary

-

Signature: _.unary(fun:Function)

-

Returns a new function which accepts only one argument and passes this -argument to fun. Additional arguments are discarded.

-
function logArgs() {
-    console.log(arguments);
-}
-
-var logOneArg = _.unary(logArgs);
-
-logOneArg("first");
-// => ["first"]
-
-logOneArg("first", "second");
-// => ["first"]
-
-

function.combinators

-
-

Functions that are combinators.

-
-
-

always

-

Signature: _.always(value:Any)

-

Aliases: _.k

-

Takes value and returns a function that will always return value.

-
var platonicForm = _.always("Eternal & Unchangeable");
-
-platonicForm();
-// => "Eternal & Unchangeable"
-
-

bound

-

Signature: _.bound(obj:Object, fname:String)

-

Returns function property of an object by name, bound to object.

-
var aristotle = {
-    name: "Aristotle",
-    telos: "flourishing",
-    stateTelos: function() {
-        return this.name + "'s telos is " + this.telos;
-    }
-};
-
-var stateAristotlesTelos = _.bound(aristotle, "stateTelos");
-
-stateAristotlesTelos();
-// => "Aristotle's Telos is flourishing"
-
-

comparator

-

Signature: _.comparator(fun:Function)

-

Takes a binary predicate-like function and returns a comparator function (return -values of -1, 0, 1) which can be used as a callback for _.sort or -Array.prototype.sort.

-
var lessOrEqual = function(x, y) { return x <= y; };
-
-var arr = [0, 1, -2];
-
-arr.sort(_.comparator(lessOrEqual));
-// => [-2, 0, 1]
-
-

complement

-

Signature: _.complement(pred:Function)

-

Returns a function that reverses the sense of a given predicate-like.

-
function isAugustine (val) {
-    return val === "Augustine";
-}
-
-isNotAugustine = _.complement(isAugustine);
-
-isNotAugustine("Dionysius");
-// => True
-
-

conjoin

-

Signature: _.conjoin(pred:Function...)

-

Composes multiple predicates into a single predicate that checks all elements -of an array for conformance to all of the original predicates.

-
function startsWithA (val) {
-    return val[0] === "A";
-}
-
-function endsWithE (val) {
-    return val[val.length - 1] === "e";
-}
-
-var names = ["Aristotle", "Aquinas", "Plato", "Augustine"];
-
-var startsAAndEndsE = _.conjoin(startsWithA, endsWithE);
-
-startsAAndEndsE(names);
-// => ["Aristotle", "Augustine"]
-
-

disjoin

-

Signature: _.disjoin(pred:Function...)

-

Composes multiple predicates into a single predicate that checks all elements -of an array for conformance to any of the original predicates.

-
function startsWithA (val) {
-    return val[0] === "A";
-}
-
-function endsWithE (val) {
-    return val[val.length - 1] === "e";
-}
-
-var names = ["Aristotle", "Aquinas", "Plato", "Augustine"];
-
-var startsAOrEndsE = _.disjoin(startsWithA, endsWithE);
-
-startsAOrEndsE(names);
-// => ["Aristotle", "Aquinas", "Augustine"]
-
-

juxt

-

Signature: _.juxt(fun:Function...)

-

Returns a function whose return value is an array of the results of calling -each of the original functions with the arguments.

-
function firstChar (val) {
-    return val[0];
-}
-
-function lastChar (val) {
-    return val[val.length - 1];
-}
-
-var firstAndLastChars = _.juxt(firstChar, lastChar);
-
-firstAndLastChars("Etruria");
-// => ["E", "a"]
-
-

flip

-

Signature: _.flip(fun:Function)

-

Returns a function that works identically to fun, but accepts the arguments -in reverse order.

-
function regionCapitol (region, capitol) {
-    return "The capitol of " + region + " is " + capitol;
-}
-
-capitolRegion = _.flip(regionCapitol);
-
-capitolRegion("Thessalonica", "Illyrica");
-// => "The capitol of Illyrica is Thessalonica"
-
-

flip2

-

Signature: _.flip2(fun:Function)

-

Returns a function that works identically to fun, but accepts the first two -arguments in reverse order. The order of all other arguments remains the same.

-
function regionCapitol (region, capitol) {
-    return "The capitol of " + region + " is " + capitol;
-}
-
-capitolRegion = _.flip2(regionCapitol);
-
-capitolRegion("Thessalonica", "Illyrica");
-// => "The capitol of Illyrica is Thessalonica"
-
-

fnull

-

Signature: _.fnull(fun:Function[, default:Any...])

-

Returns a function that protects fun from receiving non-existy values. Each -subsequent value provided to fnull acts as the default to the original -fun should a call receive non-existy values in the defaulted arg slots.

-
function getLength (val) {
-    return val.length;
-}
-
-safeGetLength = _.fnull(getLength, []);
-
-safeGetLength([1, 2, 3]);
-// => 3
-
-safeGetLength(null);
-// => 0
-
-

functionalize

-

Signature: _.functionalize(fun:Function[, default:Any...])

-

Takes a method-style function (one which uses this) and pushes this into the -argument list. The returned function uses its first argument as the -receiver/context of the original function, and the rest of the arguments are -used as the original's entire argument list.

-
var militaryUnits = {
-    centuria: "80 men",
-    cohort: "480 men",
-    getDescription: function (unitName) {
-        return this[unitName];
-    }
-};
-
-var getDescription = _.functionalize(militaryUnits.getDescription);
-
-var rulers = {
-    Leonidas: "King of Sparta",
-    Augustus: "First Roman Emperor"
-};
-
-getDescription(rulers, "Augustus");
-// => "First Roman Emperor"
-
-

mapArgs

-

Signature: _.mapArgs(fun:Function)

-

Takes a target function and returns a new function which accepts a mapping -function, which in turn returns a function that will map its arguments before -calling the original target function.

-
function doubleNum (x) { return 2 * x; }
-
-function squareNum (x) { return x * x; }
-
-var squareThenDouble = _.mapArgs(doubleNum)(squareNum);
-
-squareThenDouble(3);
-// => 18
-
-

mapArgsWith

-

Signature: _.mapArgs(mapFun:Function)

-

Takes a mapping function and returns a new combinator function which will take -a target function and return a new version which maps its arguments with the -mapping function before executing the body of the target function.

-
function doubleNum (x) { return 2 * x; }
-
-function squareNum (x) { return x * x; }
-
-var squareArgs = _.mapArgsWith(squareNum);
-
-var squareThenDouble = squareArgs(doubleNum);
-
-squareThenDouble(3);
-// => 18
-
-

methodize

-

Signature: _.methodize(func:Function)

-

Takes a function and pulls the first argument out of the argument list and into -this position. The returned function calls the original with its receiver -(this) prepending the argument list. The original is called with a receiver -of null.

-
function describe (obj) {
-    return obj.name + ": " + obj.description;
-}
-
-var democritus = {
-    name: "Democritus",
-    description: "originator of the atomic hypothesis",
-    describe: _.methodize(describe)
-};
-
-democritus.describe();
-// => "Democritus: originator of the atomic hypothesis"
-
-

pipeline

-

Signature: _.pipeline(func:Function[, func2:Function...]) or _.pipeline(funcArr:Array)

-

Aliases: _.t

-

Takes a list of functions, either as an array or as individual arguments -and returns a function that takes some value as its first argument and runs it -through a pipeline of the original functions given.

-
function halveNum (x) { return x / 2; };
-function squareNum (x) { return x * x; };
-function doubleNum (x) { return 2 * x; };
-
-var halveSquareDouble = _.pipeline(halveNum, squareNum, doubleNum);
-
-halveSquareDouble(1);
-// => 0.5
-
-var doubleSquareHalve = _.pipeline([doubleNum, squareNum, halveNum]);
-
-doubleSquareHalve(1);
-// => 2
-
-

splat

-

Signature: _.splat(fun:Function)

-

Takes a function expecting one or more arguments and returns a function -that takes an array and uses its elements as the arguments to the original -function. This roughly corresponds to the spread operator in -ECMAScript 6.

-
function listTwoNames (a, b) {
-    return a.name + " & " + b.name;
-}
-
-var listTwoNamesFromArray = _.splat(listTwoNames);
-
-listTwoNamesFromArray([{ name: "Zeno" }, { name: "Parmenides"}]);
-// => "Zeno & Parmenides"
-
-

unsplat

-

Signature: _.unsplat(fun:Function)

-

Aliases: _.unsplatr

-

Takes a function expecting an array as its last argument and returns a function -which works identically, but takes a list of trailing arguments instead. Roughly -corresponds to rest parameters in ECMAScript 6.

-
function joinWith (joiner, arr) {
-    return arr.join(joiner);
-}
-
-var joinArgsWith = _.unsplat(joinWith);
-
-joinArgsWith(" & ", "Plutarch", "Proclus");
-// => "Plutarch & Proclus"
-
-

unsplatl

-

Signature: _.unsplatl(fun:Function)

-

Similar to unsplat, but takes a function expecting an array as its -first argument and returns a function which works identically, but takes a -list of leading arguments instead. Roughly corresponds to -rest parameters in ECMAScript 6.

-
function joinWith (arr, joiner) {
-    return arr.join(joiner);
-}
-
-var joinArgsWith = _.unsplat(joinWith);
-
-joinArgsWith("Olympiodorus", "Syrianus", " & ");
-// => "Olympiodorus & Syrianus"
-
-

function.iterators

-
-

Functions to iterate over collections.

-
-
-

iterators.accumulate

-

Signature: _.iterators.accumulate(iter:Function, binaryFn:Function, initial:Any)

-

Returns a function that when called will iterate one step with iter and return -the value currently accumulated by using binaryFn. The function will return undefined once all values have been iterated over.

-
var generalsIterator = _.iterators.List(["Hannibal", "Scipio"]);
-
-function countLetters(memo, element) {
-     return memo + element.length;
-}
-
-var generalsAcc = _.iterators.accumulate(generalsIterator, countLetters, 0);
-
-generalsAcc();
-// => 8
-
-generalsAcc();
-// => 14
-
-generalsAcc();
-// => undefined
-
-

iterators.accumulateWithReturn

-

Signature: _.iterators.accumulateWithReturn(iter:Function, binaryFn:Function, initial:Any)

-

Acts similarly to accumulate, except that binaryFn is expected to return an -array of two elements. The value of the first element is given to the next run -of binaryFn. The value of the second element is yielded by the iterator.

-
var fiveIter = _.iterators.List([1, 2, 3, 4, 5]);
-
-function adderWithMessage (state, element) {
-    return [state + element, 'Total is ' + (state + element)];
-}
-
-var i = _.iterators.accumulateWithReturn(fiveIter, adderWithMessage, 0);
-
-i();
-// => "Total is 1"
-
-i();
-// => "Total is 3"
-
-i();
-// => "Total is 6"
-
-

iterators.drop

-

Signature: _.iterators.drop(iter:Function[, numberToDrop:Number])

-

Given an iterator function iter, will return a new iterator which iterates -over the same values as iter, except that the first numberToDrop values -will be omitted. If numberToDrop is not provided, it will default to 1.

-
var deityIter = _.iterators.List(["Zeus", "Apollo", "Athena", "Aphrodite"]);
-
-var goddessIter = _.iterators.drop(deityIter, 2);
-
-goddessIter();
-// => "Athena"
-
-goddessIter();
-// => "Aphrodite"
-
-

iterators.foldl

-

Signature: _.iterators.foldl(iter:Function, binaryFn:Function[, seed:Any])

-

Aliases: iterators.reduce

-

Boils down the values given by iter into a single value. The seed is the -initial state. The binaryFn is given two arguments: the seed and the -current value yielded by iter.

-
var sybylIter = _.iterators.List(["cumaean", "tiburtine"]);
-
-function commaString (a, b) { return a + ", " + b; }
-
-_.iterators.foldl(sybylIter, commaString);
-// => "cumaean, tiburtine"
-
-

iterators.K

-

Signature: _.iterators.K(value:Any)

-

Aliases: iterators.constant

-

Returns a function that when invoked will always return value.

-
var ceasar = _.iterators.K("Ceasar");
-
-ceasar();
-// => "ceasar"
-
-

iterators.List

-

Signature: _.iterators.List(array:Array)

-

Returns an iterator that when invoked will iterate over the contents of array.

-
var triumvirIter = _.iterators.List(["Ceasar", "Pompey", "Crassus"]);
-
-triumvirIter();
-// => "Ceasar"
-
-triumvirIter();
-// => "Pompey"
-
-triumvirIter();
-// => "Crassus"
-
-

iterators.map

-

Signature: _.iterators.map(iter:Function, unaryFn:Function)

-

Returns a new iterator function which on each iteration will return the result -of running iter's current value through unaryFn.

-
var notablesIter = _.iterators.List(["Socrates", "Plato"]);
-
-function postfixAthenian (val) {
-    return val + ", Athenian";
-}
-
-var notableAtheniansIter = _.iterators.map(notablesIter, postfixAthenian);
-
-notableAtheniansIter();
-// => "Socrates, Athenian"
-
-notableAtheniansIter();
-// => "Plato, Athenian"
-
-

iterators.mapcat

-

Signature: _.iterators.mapcat(iter:Function, unaryFn:Function)

-

Returns an iterator which is the result of flattening the contents of iter, -and mapping the results with unaryFn.

-
function naturalSmallerThan (x)  {
-    return _.iterators.List(_.range(0, x));
-}
-
-var treeIter = _.iterators.Tree([1, [2]]);
-
-var smallerThanIter = _.iterators.mapcat(treeIter, naturalSmallerThan);
-
-smallerThanIter();
-// => 0
-
-smallerThanIter();
-// => 0
-
-smallerThanIter();
-// => 1
-
-

iterators.numbers

-

Signature: _.iterators.numbers([start:Number])

-

Returns an iterator of integers which will begin with start and increment by -one for each invocation. If start is not provided it will default to 1.

-
var twoAndUp = _.iterators.numbers(2);
-
-twoAndUp();
-// => 2
-
-twoAndUp();
-// => 3
-
-twoAndUp();
-// => 4
-
-

iterators.range

-

Signature: _.iterators.range([from:Number, to:Number, by:Number])

-

Returns an iterator whose values consist of numbers beginning with from, ending with to, in steps of size by.

-
var by5 = _.iterators.range(5, Infinity, 5);
-
-by5();
-// => 5
-
-by5();
-// => 10
-
-by5();
-// => 15
-
-

iterators.reject

-

Signature: _.iterators.reject(iter:Function, unaryPredicatFn:Function)

-

Returns an iterator consisting of the values of iter which are not flagged -true by unaryPredicateFn.

-
var philosophers = ["Anaximander", "Socrates", "Heraclitus"];
-
-var philosophersIter = _.iterators.List(philosophers);
-
-function isSocrates (val) {
-    return val === "Socrates";
-}
-
-var preSocraticsIter = _.iterators.reject(philosophersIter, isSocrates);
-
-preSocraticsIter()
-// => "Anaximander"
-
-preSocraticsIter()
-// => "Heraclitus"
-
-

iterators.select

-

Signature: _.iterators.select(iter:Function, unaryPredicatFn:Function)

-

Aliases: iterators.find, iteraters.filter

-

Returns an iterator consisting of the values of iter which are flagged -true by unaryPredicateFn.

-
var philosophers = ["Anaximander", "Socrates", "Heraclitus"];
-
-var philosophersIter = _.iterators.List(philosophers);
-
-function isSocrates (val) {
-    return val === "Socrates";
-}
-
-var socraticIter = _.iterators.select(philosophersIter, isSocrates);
-
-socraticIter()
-// => "Socrates"
-
-

iterators.slice

-

Signature: _.iterators.slice(iter:Function, numberToDrop:Number, numberToTake:Number)

-

Returns an iterator whose values consist of iter's after removing -numberToDrop from the head, and a maxiumum of numberToTake of the remaining. -If numberToTake is not specified, all of iter's remaining values will be -used.

-
var emperors = ["Augustus", "Tiberius", "Caligula", "Claudius"];
-
-var emperorsIter = _.iterators.List(emperors);
-
-var middleEmperorsIter = _.iterators.slice(emperorsIter, 1, 2);
-
-middleEmperorsIter();
-// => "Tiberius"
-
-middleEmperorsIter();
-// => "Caligula"
-
-middleEmperorsIter();
-// => undefined
-
-

iterators.take

-

Signature: _.iterators.take(iter:Function[, numberToTake:Number])

-

Returns an iterator consisting of the first numberToTake values yielded by -iter. If numberToTake is not provided, it will default to 1.

-
var byzantineEmperors = ["Constantine", "Constantius", "Constans"];
-
-var byzantineEmperorsIter = _.iterators.List(byzantineEmperors);
-
-var firstTwoEmperorsIter = _.iterators.take(byzantineEmperorsIter, 2);
-
-firstTwoEmperorsIter();
-// => "Constantine"
-
-firstTwoEmperorsIter();
-// => "Constantius"
-
-firstTwoEmperorsIter();
-// => undefined
-
-

iterators.Tree

-

Signature: _.iterators.Tree(array:Array);

-

Returns an iterator that yields the individual values of a tree array.

-
var rulers = ["Augustus", ["Constantine"], ["Leo", ["Charlemagne"]]];
-
-var rulersIter = _.iterators.Tree(rulers);
-
-rulersIter();
-// => "Augustus"
-
-rulersIter();
-// => "Constantine"
-
-rulersIter();
-// => "Leo"
-
-rulersIter();
-// => "Charlemagne"
-
-

iterators.unfold

-

Signature: _.iterators.unfold(seed:Any, unaryFn:Function)

-
function greatify (val) {
-    return val + " the Great";
-}
-
-var greatIter = _.iterators.unfold("Constantine", greatify);
-
-greatIter();
-// => "Constantine the Great"
-
-greatIter();
-// => "Constantine the Great the Great"
-
-greatIter();
-// => "Constantine the Great the Great the Great"
-
-

iterators.unfoldWithReturn

-

Signature: _.iterators.unfold(seed:Any, unaryFn:Function)

-

Acts similarly to unfold, except that unaryFn is expected to return an array -with two elements. The value of the first element is given to the next run of -unaryFn. The value of the second element is yielded by the iterator.

-
var i = _.iterators.unfoldWithReturn(1, function(n) {
-    return [n + 1, n * n];
-});
-
-i();
-// => 1
-
-i();
-// => 4
-
-i();
-// => 9
-

function.predicates

-
-

Functions which return whether the input meets a condition.

-
-
-

isAssociative

-

Signature: isAssociative(value:Any)

-

Returns a boolean indicating whether or not the value is an associative object. -An associative object is one where its elements can be accessed via a key or -index (e.g. arrays, arguments, objects).

-
_.isAssociative(["Athens", "Sparta"]);
-// => true
-
-_.isAssociative(42);
-// => false
-
-

isDecreasing

-

Signature: _.isDecreasing(values:Any...)

-

Checks whether the arguments are monotonically decreasing values (i.e. whether -each argument is less than the previous argument.)

-
_.isDecreasing(3, 2, 1);
-// => true
-
-_.isDecreasing(15, 12, 2);
-// => true
-
-_.isDecreasing(2, 3);
-// => false
-
-

isEven

-

Signature: _.isEven(value:Any)

-

Checks whether the value is an even number.

-
_.isEven(12);
-// => true
-
-_.isEven(3);
-// => false
-
-_.isEven({});
-// => false
-
-

isFloat

-

Signature: _.isFloat(value:Any)

-

Checks whether the value is a "float." For the purposes of this function, a float -is a numeric value that is not an integer. A numeric value may be a number, a -string containing a number, a Number object, etc.

-

NOTE: JavaScript itself makes no distinction between integers and floats. For -the purposes of this function both 1 and 1.0 are considered integers.

-
_.isFloat(1.1);
-// => true
-
-_.isFloat(1);
-// => false
-
-_.isFloat(1.0);
-// => false
-
-_.isFloat("2.15");
-// => true
-
-

isIncreasing

-

Signature: _.isIncreasing(value:Any...)

-

Checks whether the arguments are monotonically increasing values (i.e. each -argument is greater than the previous argument.)

-
_.isIncreasing(1, 12, 15);
-// => true
-
-_.isIncreasing(1);
-// => true
-
-_.isIncreasing(5, 4);
-// => false
-
-

isIndexed

-

Signature: _.isIndexed(value:Any)

-

Checks whether the value is "indexed." An indexed value is one which accepts a -numerical index to access its elements. (e.g. arrays and strings)

-

NOTE: Underscore does not support cross-browser consistent use of strings as -array-like values, so be wary in IE 8 when using string objects and in IE7 and -earlier when using string literals & objects.

-
_.isIndexed("Socrates");
-// => true
-
-_.isIndexed({poison: "hemlock"});
-// => false
-
-

isInstanceOf

-

Signature: _.isInstanceOf(value:Any, constructor:Function)

-

Checks whether the value is an instance of the constructor.

-
_.isInstanceOf(new Date(), Date);
-// => true
-
-_.isInstanceOf("Hippocrates", RegExp);
-// => false
-
-

isInteger

-

Signature: _.isInteger(value:Any)

-

Checks whether the value is a numeric integer. A numeric value can be a string -containing a number, a Number object, etc.

-
_.isInteger(18);
-// => true
-
-_.isInteger("18");
-// => true
-
-_.isInteger(2.5);
-// => false
-
-_.isInteger(-1);
-// => true
-
-

isJSON

-

Signature: _.isJSON(value:Any)

-

Checks whether the value is valid JSON. See the spec for -more information on what constitutes valid JSON.

-

NOTE: This function relies on JSON.parse which is not available in IE7 and -earlier.

-
_.isJSON('{ "name": "Crockford" }');
-// => true
-
-_.isJSON({ name: "Crocket" });
-// => false
-
-

isNegative

-

Signature: _.isNegative(value:Any)

-

Checks whether the value is a negative number.

-
_.isNegative(-2);
-// => true
-
-_.isNegative(5);
-// => false
-
-

isNumeric

-

Signature: _.isNumeric(value:Any)

-

A numeric is something that contains a numeric value, regardless of its type. It -can be a string containing a numeric value, exponential notation, a Number -object, etc.

-
_.isNumeric("14");
-// => true
-
-_.isNumeric("fourteen");
-// => false
-
-

isOdd

-

Signature: _.isOdd(value:Any)

-

Checks whether the value is an odd number.

-
_.isOdd(3);
-// => true
-
-_.isOdd(2);
-// => false
-
-_.isOdd({});
-// => false
-
-

isPlainObject

-

Signature: _.isPlainObject(value:Any);

-

Checks whether the value is a "plain" object created as an object literal ({}) -or explicitly constructed with new Object(). Instances of other constructors -are not plain objects.

-
_.isPlainObject({});
-// => true
-
-_.isPlainObject(new Date());
-// => false
-
-_.isPlainObject([]);
-// => false
-
-

isPositive

-

Signature: _.isPositive(value:Any)

-

Checks whether the value is a positive number.

-
_.isPositive(21);
-// => true
-
-_.isPositive(-3);
-// => false
-
-

isSequential

-

Signature: _.isSequential(value:Any)

-

Checks whether the value is a sequential composite type (i.e. arrays and -arguments).

-
_.isSequential(["Herodotus", "Thucidydes");
-// => true
-
-_.isSequential(new Date);
-// => false
-
-

isValidDate

-

Signature: _.isValidDate(value:Any)

-

Checks whether the value is a valid date. That is, the value is both an instance -of Date and it represents an actual date.

-

Warning: This function does not verify -whether the original input to Date is a real date. For instance, -new Date("02/30/2014") is considered a valid date because Date coerces that -into a representation of 03/02/2014. To validate strings representing a date, -consider using a date/time library like Moment.js.

-
_.isValidDate(new Date("January 1, 1900"));
-// => true
-
-_.isValidDate(new Date("The Last Great Time War"));
-// => false
-
-

isZero

-

Signature: _.isZero(value:Any)

-

Checks whether the value is 0.

-
_.isZero(0);
-// => true
-
-_.isZero("Pythagoras");
-// => false
-
-

object.builders

-
-

Functions to build objects.

-
-
-

frequencies

-

Signature: _.frequencies(arr:Array)

-

Returns an object whose property keys are the values of arr's elements. The -property values are a count of how many times that value appeared in arr.

-
var citations = ["Plato", "Aristotle", "Plotinus", "Plato"];
-
-_.frequencies(citations);
-// => { Plato: 2, Aristotle: 1, Plotinus: 1 }
-
-

merge

-

Signature: _.merge(obj1:Object[, obj:Object...])

-

Merges two or more objects starting with the left-most and applying the keys -rightward.

-
_.merge({ a: "alpha" }, { b: "beta" });
-// => { a: "alpha", b: "beta" }
-
-

renameKeys

-

Signature: _.renameKeys(obj:Object, keyMap:Object)

-

Takes an object (obj) and a map of keys (keyMap) and returns a new object -where the keys of obj have been renamed as specified in keyMap.

-
_.renameKeys({ a: 1, b: 2 }, { a: "alpha", b: "beta" });
-// => { alpha: 1, beta: 2 }
-
-

setPath

-

Signature: _.setPath(obj:Object, value:Any, ks:Array, defaultValue:Any)

-

Sets the value of a property at any depth in obj based on the path described -by the ks array. If any of the properties in the ks path don't exist, they -will be created with defaultValue.

-

See _.updatePath about obj not being mutated in the process by cloning it.

-
_.setPath({}, "Plotinus", ["Platonism", "Neoplatonism"], {});
-// => { Platonism: { Neoplatonism: "Plotinus" } }
-
-

snapshot

-

Signature: _.snapshot(obj:Object)

-

Snapshots/clones an object deeply.

-
var schools = { plato: "Academy", aristotle: "Lyceum" };
-
-_.snapshot(schools);
-// => { plato: "Academy", aristotle: "Lyceum" }
-
-schools === _.snapshot(schools);
-// => false
-
-

Signature: _.updatePath(obj:Object, fun:Function, ks:Array, defaultValue:Any)

-

Updates the value at any depth in a nested object based on the path described by -the ks array. The function fun is called with the current value and is -expected to return a replacement value. If no keys are provided, then the -object itself is presented to fun. If a property in the path is missing, then -it will be created with defaultValue.

-

Note that the original object will not be mutated. Instead, obj will -be cloned deeply.

-
var imperialize = function (val) {
-    if (val == "Republic") return "Empire";
-    else return val;
-};
-
-_.updatePath({ rome: "Republic" }, imperialize,  ["rome"]);
-// => { rome: "Empire" }
-
-var obj = { earth: { rome: "Republic" } };
-var imperialObj = _.updatePath(obj, imperialize, ["earth", "rome"]);
-
-imperialObj;
-// => { earth: { rome: "Empire" }}
-
-obj;
-// => { earth: { rome: "Republic" }}
-
-obj === imperialObj;
-// => false
-

object.selectors

-
-

Functions to select values from an object.

-
-
-

accessor

-

Signature: _.accessor(field:String)

-

Returns a function that will attempt to look up a named field in any object -that it is given.

-
var getName = _.accessor('name');
-
-getName({ name: 'Seneca' });
-// => 'Seneca'
-
-

dictionary

-

Signature: _.dictionary(obj:Object)

-

Given an object, returns a function that will attempt to look up a field that -it is given.

-
var generals = {
-    rome: "Scipio",
-    carthage: "Hannibal"
-};
-
-var getGeneralOf = _.dictionary(generals);
-
-getGeneralOf("rome");
-// => "Scipio"
-
-

getPath

-

Signature: _.getPath(obj:Object, ks:String|Array)

-

Gets the value at any depth in a nested object based on the path described by -the keys given. Keys may be given as an array of key names or as a single string -using JavaScript property access notation. -Returns undefined if the path cannot be reached.

-
var countries = {
-        greece: {
-            athens: {
-                playwright:  "Sophocles"
-            },
-            notableFigures: ["Alexander", "Hippocrates", "Thales"]
-        }
-    }
-};
-
-_.getPath(countries, "greece.athens.playwright");
-// => "Sophocles"
-
-_.getPath(countries, "greece.sparta.playwright");
-// => undefined
-
-_.getPath(countries, ["greece", "athens", "playwright"]);
-// => "Sophocles"
-
-_.getPath(countries, ["greece", "sparta", "playwright"]);
-// => undefined
-
-_.getPath(countries, ["greece", "notableFigures", 1]);
-// => "Hippocrates"
-
-_.getPath(countries, "greece.notableFigures[2]");
-// => "Thales"
-
-_.getPath(countries, "greece['notableFigures'][2]")
-// => "Thales"
-
-

hasPath

-

Signature: _.hasPath(obj:Object, ks:String|Array)

-

Returns a boolean indicating whether there is a property at the path described -by the keys given. Keys may be given as an array of key names or as a single string -using JavaScript property access notation.

-
var countries = {
-        greece: {
-            athens: {
-                playwright:  "Sophocles"
-            },
-            notableFigures: ["Alexander", "Hippocrates", "Thales"]
-        }
-    }
-};
-
-_.hasPath(countries, "greece.athens.playwright");
-// => true
-
-_.hasPath(countries, "greece.sparta.playwright");
-// => false
-
-_.hasPath(countries, ["greece", "athens", "playwright"]);
-// => true
-
-_.hasPath(countries, ["greece", "sparta", "playwright"]);
-// => false
-
-_.hasPath(countries, ["greece", "notableFigures", 1]);
-// => true
-
-_.hasPath(countries, "greece.notableFigures[2]");
-// => true
-
-_.hasPath(countries, "greece['notableFigures'][2]");
-// => true
-
-_.hasPath(countries, "greece.sparta[2]");
-// => false
-
-

keysFromPath

-

Signature: _.keysFromPath(path:String)

-

Takes a string in JavaScript object path notation and returns an array of keys.

-
_.keysFromPath("rome.emperors[0]['first-name']");
-// => ["rome", "emperors", "0", "first-name"]
-
-

kv

-

Signature: _.kv(obj:Object, key:String)

-

Returns the key/value pair for a given property in an object, undefined if not found.

-
var playAuthor = {
-    "Medea": "Aeschylus"
-};
-
-_.kv(playAuthor, "Medea");
-// => ["Medea", "Aeschylus"]
-
-_.kv(playAuthor, "Hamlet");
-// => undefined
-
-

omitWhen

-

Signature: _.omitWhen(obj, pred:Function)

-

Returns a copy of obj omitting any properties that the predicate (pred) -function returns true for. The predicat function is invoked with each -property value, like so: pred(propValue).

-
var playwrights = {
-    euripedes: "Greece",
-    shakespere: "England"
-};
-
-_.omitWhen(obj, function (country) { return country == "England" });
-// => { euripedes: "Greece" }
-
-

pickWhen

-

Signature: _.pickWhen(obj:Object, pred:Function)

-

Returns a copy of obj containing only properties that the predicate (pred) -function returns true for. The predicate function is invoked with each -property value, like so: pred(propValue).

-
var playwrights = {
-    euripedes: "Greece",
-    shakespere: "England"
-};
-
-_.pickWhen(obj, function (country) { return country == "England" });
-// => { shakespeare: "England" }
-
-

selectKeys

-

Signature: `_.selectKeys(obj:Object, ks:Array);

-

Returns a copy of obj containing only the properties listed in the ks array.

-
var philosopherCities = {
-    Philo: "Alexandria",
-    Plato: "Athens",
-    Plotinus: "Rome"
-}
-
-_.selectKeys(philosopherCities, ["Plato", "Plotinus"]);
-// => { Plato: "Athens", Plotinus: "Rome" }
-

util.existential

-
-

Functions which deal with whether a value "exists."

-
-
-

exists

-

Signature: _.exists(value:Any)

-

Checks whether or not the value is "existy." Both null and undefined are -considered non-existy values. All other values are existy.

-
_.exists(null);
-// => false
-
-_.exists(undefined);
-// => false
-
-_.exists({});
-// = > true
-
-_.exists("Sparta");
-// => true
-
-

falsey

-

Signature: _.falsey(value:Any)

-

Checks whether the value is falsey. A falsey value is one which coerces to -false in a boolean context.

-
_.falsey(0);
-// => true
-
-_.falsey("");
-// => true
-
-_.falsey({});
-// => false
-
-_.falsey("Corinth");
-// => false
-
-

firstExisting

-

Signature: _.firstExisting(value:Any[, value:Any...])

-

Returns the first existy argument from the argument list.

-
_.firstExisting("Socrates", "Plato");
-// => "Socrates"
-
-_.firstExisting(null, undefined, "Heraclitus");
-// => "Heraclitus"
-
-

not

-

Signature: _.not(value:Any)

-

Returns a boolean which is the opposite of the truthiness of the original value.

-
_.not(0);
-// => true
-
-_.not(1);
-// => false
-
-_.not(true);
-// => false
-
-_.not(false);
-// => true
-
-_.not({});
-// => false
-
-_.not(null);
-// => true
-
-

truthy

-

Signature: _.truthy(value:Any)

-

Checks whether the value is truthy. A truthy value is one which coerces to -true in a boolean context.

-
_.truthy({});
-// => true
-
-_.truthy("Athens");
-// => true
-
-_.truthy(0);
-// => false
-
-_.truthy("");
-// => false
-
-

util.operators

-
-

Functions which wrap JavaScript's operators.

-
-
-

add

-

Signature: _.add(value:Number, value:Number[, value:Number...]), _.add(values:Array)

-

Returns the sum of the arguments.

-
_.add(1, 2, 3, 4);
-// => 10
-
-_.add([1, 2, 3, 4]);
-// => 10
-
-

bitwiseAnd

-

Signature: _.bitwiseAnd(value:Any, value:Any[, value:Any...]), _.bitwiseAnd(values:Array)

-

Returns the result of using the & operator on the arguments.

-
_.bitwiseAnd(1, 3);
-// => 1
-
-_.bitwiseAnd(1, 3, 2);
-// => 0
-
-_.bitwiseAnd([1, 3, 2]);
-// => 0
-
-

bitwiseLeft

-

Signature: _.bitwiseLeft(value:Any, value:Any[, value:Any...]), _.bitwiseLeft(values:Array)

-

Returns the result of using the << operator on the arguments.

-
_.bitwiseLeft(1, 3);
-// => 8
-
-_.bitwiseLeft(1, 3, 2);
-// => 32
-
-_.bitwiseLeft([1, 3, 2]);
-// => 32
-
-

bitwiseRight

-

Signature: _.bitwiseRight(value:Any, value:Any[, value:Any...]), _.bitwiseRight(values:Array)

-

Returns the result of using the >> operator on the arguments.

-
_.bitwiseRight(3, 1);
-// => 1
-
-_.bitwiseRight(3, 1, 3);
-// => 0
-
-_.bitwiseRight([3, 1, 3]);
-// => 0
-
-

bitwiseNot

-

Signature: _.bitwiseNot(value:Any)

-

Returns the result of using the ~ operator on the value.

-
_.bitwiseNot(1);
-// => -2
-
-_.bitwiseNot(2);
-// => -3
-
-

bitwiseOr

-

Signature: _.bitwiseOr(value:Any, value:Any[, value:Any...]), _.bitwiseOr(values:Array)

-

Returns the result of using the | operator on the arguments.

-
_.bitwiseOr(1, 3);
-// => 3
-
-_.bitwiseOr(1, 3, 4);
-// => 7
-
-_.bitwiseOr([1, 3, 4]);
-// => 7
-
-

bitwiseXor

-

Signature: _.bitwiseXor(value:Any, value:Any[, value:Any...]),_.bitwiseXor(values:Array)

-

Returns the result of using the ^ operator on the arguments.

-
_.bitwiseXor(1, 3);
-// => 2
-
-_.bitwiseXor(1, 3, 3);
-// => 1
-
-_.bitwiseXor([1, 3, 3]);
-// => 1
-
-

bitwiseZ

-

Signature: _.bitwiseZ(value:Any, value:Any[, value:Any...]), _.bitwiseZ(values:Array)

-

Returns the result of using the >>> operator on the arguments.

-
_.bitwiseZ(72, 32);
-// => 72
-
-_.bitwiseZ(72, 32, 2);
-// => 18
-
-_.bitwiseZ([72, 32, 2]);
-// => 18
-
-

dec

-

Signature: _.dec(value:Number)

-

Returns the result of decrementing the value by 1.

-
_.dec(2);
-// => 1
-
-

div

-

Signature: _.div(value:Number, value:Number[, value:Number...]), _.div(values:Array)

-

Returns the quotient of the arguments.

-
_.div(8, 2);
-// => 4
-
-_.div(8, 2, 2);
-// => 2
-
-_.div([8, 2, 2]);
-// => 2
-
-

eq

-

Signature: _.eq(value:Any, value:Any[, value:Any...]),_.eq(values:Array)

-

Compares the arguments with loose equality (==).

-
_.eq(1, "1");
-// => true
-
-_.eq(1, 15);
-// => false
-
-_.eq(1, true, "1");
-// => true
-
-_.eq(1, 1, 15);
-// => false
-
-_.eq([1, 1, 15]);
-// => false
-
-

gt

-

Signature: _.gt(value:Any, value:Any[, value:Any...]), _.gt(values:Array)

-

Checks whether each argument is greater than the previous argument.

-
_.gt(1, 2);
-// => true
-
-_.gt(1, 2, 3);
-// => true
-
-_.gt(1, 6, 2);
-// => false
-
-_.gt([1, 6, 2]);
-// => false
-
-

gte

-

Signature: _.gte(value:Any, value:Any[, value:Any...]), _.gte(values:Array)

-

Checks whether each argument is greater than or equal to the previous argument.

-
_.gte(1, 2);
-// => true
-
-_.gte(1, 1, 3);
-// => true
-
-_.gte(1, 6, 2);
-// => false
-
-_.gte([1, 6, 2]);
-// => false
-
-

inc

-

Signature: _.inc(value:Number)

-

Returns the result of incrementing the value by 1.

-
_.inc(2);
-// => 3
-
-

lt

-

Signature: _.lt(value:Any, value:Any[, value:Any...]), _.lt(values:Array)

-

Checks whether each argument is less than the previous argument.

-
_.lt(2, 1);
-// => true
-
-_.lt(2, 1, 0);
-// => true
-
-_.lt(2, 1, 12);
-// => false
-
-_.lt([2, 1, 12]);
-// => false
-
-

lte

-

Signature: _.lte(value:Any, value:Any[, value:Any...]), _.lte(values:Array)

-

Checks whether each argument is less than or equal to the previous argument.

-
_.lte(2, 1);
-// => true
-
-_.lte(2, 1, 1);
-// => true
-
-_.lte(2, 1, 12);
-// => false
-
-_.lte([2, 1, 12]);
-// => false
-
-

mul

-

Signature: _.mul(value:Number, value:Number[, value:Number...]), _.mul(values:Array)

-

Returns the product of the arguments.

-
_.mul(1, 2, 3, 4);
-// => 24
-
-_.mul([1, 2, 3, 4]);
-// => 24
-
-

mod

-

Signature: _.mod(dividend:Number, divisor:Number)

-

Returns the remainder of dividing dividend by divisor.

-
_.mod(26, 5);
-// => 1
-
-_.mod(14, 3);
-// => 2
-
-

neg

-

Signature: _.neg(num:Number)

-

Returns a new number with the opposite sign value of num.

-
_.neg(5);
-// => -5
-
-_.neg(-3);
-// => 3
-
-

neq

-

Signature: _.neq(value:Any, value:Any[, value:Any...]), _.neq(values:Array)

-

Checks whether each argument is not equal to the previous argument, using loose -inequality (!=).

-
_.neq(2, 1);
-// => true
-
-_.neq(2, 1, 1);
-// => true
-
-_.neq(1, 1);
-// => false
-
-_.neq([1, 1]);
-// => false
-
-

not

-

Signature: _.not(value:Any)

-

Returns a boolean which is the opposite of the truthiness of the original value.

-
_.not(0);
-// => true
-
-_.not(1);
-// => false
-
-_.not(true);
-// => false
-
-_.not(false);
-// => true
-
-_.not({});
-// => false
-
-_.not(null);
-// => true
-
-

seq

-

Signature: _.seq(value:Any, value:Any[, value:Any...]), _.seq(values:Array)

-

Checks whether the arguments are strictly equal (===) to each other.

-
_.seq(2, 2);
-// => true
-
-_.seq(2, "2");
-// => false
-
-_.seq(2, 2, 2);
-// => true
-
-_.seq([2, 2, 2]);
-// => true
-
-

sneq

-

Signature: _.sneq(value:Any, value:Any[, value:Any...]), _.sneq(values:Array)

-

Checks whether the arguments are strictly not equal (!==) to each other.

-
_.sneq(2, 2);
-// => false
-
-_.sneq(2, "2");
-// => true
-
-_.sneq(2, 2, 2);
-// => false
-
-_.sneq([2, 2, 2]);
-// => false
-
-

sub

-

Signature: _.sub(value:Number, value:Number[, value:Number...]), _.sub(values:Array)

-

Returns the difference of the arguments.

-
_.sub(10, 3);
-// => 7
-
-_.sub(10, 3, 5);
-// => 2
-
-_.sub([10, 3, 5]);
-// => 2
-

util.strings

-
-

Functions for working with strings.

-
-
-

camelCase

-

Signature: _.camelCase(string:String)

-

Converts a dash-separated string to camel case. Opposite of toDash.

-
_.camelCase("ancient-greece");
-// => "ancientGreece"
-
-

explode

-

Signature: _.explode(s:String)

-

Explodes a string into an array of characters. Opposite of implode.

-
_.explode("Plato");
-// => ["P", "l", "a", "t", "o"]
-
-

fromQuery

-

Signature: _.fromQuery(str:String)

-

Takes a URL query string and converts it into an equivalent JavaScript object. -Opposite of toQuery

-
_.fromQuery("forms%5Bperfect%5D=circle&forms%5Bimperfect%5D=square");
-// => { forms: { perfect: "circle", imperfect: "square" } }
-
-

implode

-

Signature: _.implode(a:Array)

-

Implodes an array of strings into a single string. Opposite of explode.

-
_.implode(["H", "o", "m", "e", "r"]);
-// => "Homer"
-
-

strContains

-

Signature: _.strContains(str:String, search:String)

-

Reports whether a string contains a search string.

-
_.strContains("Acropolis", "polis");
-// => true
-
-

toDash

-

Signature: _.toDash(string:String)

-

Converts a camel case string to a dashed string. Opposite of camelCase.

-
_.toDash("thisIsSparta");
-// => "this-is-sparta"
-
-

toQuery

-

Signature: _.toQuery(obj:Object)

-

Takes an object and converts it into an equivalent URL query string. Opposite -of fromQuery.

-
_.toQuery({ forms: { perfect: "circle", imperfect: "square" } });
-// => "forms%5Bperfect%5D=circle&forms%5Bimperfect%5D=square"
-
-

util.trampolines

-
-

Trampoline functions.

-
-
-

done

-

Signature: _.done(value:Any)

-

A utility for wrapping a function's return values so they can be used by -_.trampoline. See below.

-
-

trampoline

-

Signature: _.trampoline(fun:Function[, args:Any...])

-

Provides a way of creating recursive functions that won't exceed a JavaScript -engine's maximum recursion depth. Rather than writing a naive recursive -function, the function's base cases must return _.done(someValue), and -recursive calls must be wrapped in a returned function.

-

In order to create a trampolined function that can be used in the same way as -a naive recursive function, use _.partial as illustrated below.

-
function isEvenNaive (num) {
-    if (num === 0) return true;
-    if (num === 1) return false;
-    return isEvenNaive(num - 2);
-}
-
-isEvenNaive(99999);
-// => InternalError: too much recursion
-
-function isEvenInner (num) {
-    if (num === 0) return _.done(true);
-    if (num === 1) return _.done(false);
-    return function () { return isEvenInner(Math.abs(num) - 2); };
-}
-
-_.trampoline(isEvenInner, 99999);
-// => false
-
-var isEven = _.partial(_.trampoline, isEvenInner);
-
-isEven(99999);
-// => false
-
-

Changelog

-

0.3.0

- - - - diff --git a/package.json b/package.json index 7da9fc4..aec1229 100644 --- a/package.json +++ b/package.json @@ -3,18 +3,21 @@ "version": "0.3.0", "main": "index.js", "dependencies": { - "underscore": "1.7.0" + "underscore": "1.10.2" }, "devDependencies": { - "grunt": "~0.4.1", - "grunt-cli": "~0.1.11", - "grunt-contrib-concat": "0.3.0", - "grunt-contrib-jshint": "^0.10.0", - "grunt-contrib-qunit": "~0.2.2", - "grunt-contrib-uglify": "0.2.0", - "grunt-contrib-watch": "~0.5.3", - "grunt-docco": "~0.3.0", - "grunt-tocdoc": "0.1.1" + "grunt": "^1.3.0", + "grunt-cli": "^1.3.2", + "grunt-contrib-concat": "1.0.1", + "grunt-contrib-jshint": "^2.1.0", + "grunt-contrib-qunit": "^4.0.0", + "grunt-contrib-uglify": "^5.0.0", + "grunt-contrib-watch": "^1.1.0", + "grunt-docco": "~0.5.0", + "grunt-tocdoc": "0.1.1", + "jquery": "3.5.1", + "jslitmus": "^0.1.0", + "qunit": "^2.11.0" }, "repository": { "type": "git", @@ -27,7 +30,10 @@ "url": "http://www.fogus.me" }, "scripts": { - "test": "node ./node_modules/grunt-cli/bin/grunt test" + "test": "grunt test", + "dist": "grunt dist", + "tocdoc": "grunt tocdoc", + "docco": "grunt docco" }, "homepage": "https://github.com/documentcloud/underscore-contrib" } diff --git a/test/array.builders.js b/test/array.builders.js index 02e8f41..07d406b 100644 --- a/test/array.builders.js +++ b/test/array.builders.js @@ -1,220 +1,220 @@ $(document).ready(function() { - module("underscore.array.builders"); + QUnit.module("underscore.array.builders"); - test("cat", function() { + QUnit.test("cat", function(assert) { // no args - deepEqual(_.cat(), [], 'should return an empty array when given no args'); - + assert.deepEqual(_.cat(), [], 'should return an empty array when given no args'); + // one arg - deepEqual(_.cat([]), [], 'should concatenate one empty array'); - deepEqual(_.cat([1,2,3]), [1,2,3], 'should concatenate one homogenious array'); + assert.deepEqual(_.cat([]), [], 'should concatenate one empty array'); + assert.deepEqual(_.cat([1,2,3]), [1,2,3], 'should concatenate one homogenious array'); var result = _.cat([1, "2", [3], {n: 4}]); - deepEqual(result, [1, "2", [3], {n: 4}], 'should concatenate one heterogenious array'); + assert.deepEqual(result, [1, "2", [3], {n: 4}], 'should concatenate one heterogenious array'); result = (function(){ return _.cat(arguments); })(1, 2, 3); - deepEqual(result, [1, 2, 3], 'should concatenate the arguments object'); + assert.deepEqual(result, [1, 2, 3], 'should concatenate the arguments object'); // two args - deepEqual(_.cat([1,2,3],[4,5,6]), [1,2,3,4,5,6], 'should concatenate two arrays'); + assert.deepEqual(_.cat([1,2,3],[4,5,6]), [1,2,3,4,5,6], 'should concatenate two arrays'); result = (function(){ return _.cat(arguments, [4,5,6]); })(1,2,3); - deepEqual(result, [1,2,3,4,5,6], 'should concatenate an array and an arguments object'); + assert.deepEqual(result, [1,2,3,4,5,6], 'should concatenate an array and an arguments object'); // > 2 args var a = [1,2,3]; var b = [4,5,6]; var c = [7,8,9]; var d = [0,0,0]; - deepEqual(_.cat(a,b,c), [1,2,3,4,5,6,7,8,9], 'should concatenate three arrays'); - deepEqual(_.cat(a,b,c,d), [1,2,3,4,5,6,7,8,9,0,0,0], 'should concatenate four arrays'); + assert.deepEqual(_.cat(a,b,c), [1,2,3,4,5,6,7,8,9], 'should concatenate three arrays'); + assert.deepEqual(_.cat(a,b,c,d), [1,2,3,4,5,6,7,8,9,0,0,0], 'should concatenate four arrays'); result = (function(){ return _.cat(arguments,b,c,d); }).apply(null, a); - deepEqual(result, [1,2,3,4,5,6,7,8,9,0,0,0], 'should concatenate four arrays, including an arguments object'); + assert.deepEqual(result, [1,2,3,4,5,6,7,8,9,0,0,0], 'should concatenate four arrays, including an arguments object'); // heterogenious types - deepEqual(_.cat([1],2), [1,2], 'should concatenate mixed types'); - deepEqual(_.cat([1],2,3), [1,2,3], 'should concatenate mixed types'); - deepEqual(_.cat(1,2,3), [1,2,3], 'should concatenate mixed types'); + assert.deepEqual(_.cat([1],2), [1,2], 'should concatenate mixed types'); + assert.deepEqual(_.cat([1],2,3), [1,2,3], 'should concatenate mixed types'); + assert.deepEqual(_.cat(1,2,3), [1,2,3], 'should concatenate mixed types'); result = (function(){ return _.cat(arguments, 4,5,6); })(1,2,3); - deepEqual(result, [1,2,3,4,5,6], 'should concatenate mixed types, including an arguments object'); + assert.deepEqual(result, [1,2,3,4,5,6], 'should concatenate mixed types, including an arguments object'); }); - test("cons", function() { - deepEqual(_.cons(0, []), [0], 'should insert the first arg into the array given as the second arg'); - deepEqual(_.cons(1, [2]), [1,2], 'should insert the first arg into the array given as the second arg'); - deepEqual(_.cons([0], [1,2,3]), [[0],1,2,3], 'should insert the first arg into the array given as the second arg'); - deepEqual(_.cons(1, 2), [1,2], 'should create a pair if the second is not an array'); - deepEqual(_.cons([1], 2), [[1],2], 'should create a pair if the second is not an array'); + QUnit.test("cons", function(assert) { + assert.deepEqual(_.cons(0, []), [0], 'should insert the first arg into the array given as the second arg'); + assert.deepEqual(_.cons(1, [2]), [1,2], 'should insert the first arg into the array given as the second arg'); + assert.deepEqual(_.cons([0], [1,2,3]), [[0],1,2,3], 'should insert the first arg into the array given as the second arg'); + assert.deepEqual(_.cons(1, 2), [1,2], 'should create a pair if the second is not an array'); + assert.deepEqual(_.cons([1], 2), [[1],2], 'should create a pair if the second is not an array'); result = (function(){ return _.cons(0, arguments); })(1,2,3); - deepEqual(result, [0,1,2,3], 'should construct an array given an arguments object as the tail'); + assert.deepEqual(result, [0,1,2,3], 'should construct an array given an arguments object as the tail'); var a = [1,2,3]; var result = _.cons(0,a); - deepEqual(a, [1,2,3], 'should not modify the original tail'); + assert.deepEqual(a, [1,2,3], 'should not modify the original tail'); }); - test("chunk", function() { + QUnit.test("chunk", function(assert) { var a = _.range(4); var b = _.range(5); var c = _.range(7); - deepEqual(_.chunk(a, 2), [[0,1],[2,3]], 'should chunk into the size given'); - deepEqual(_.chunk(b, 2), [[0,1],[2,3]], 'should chunk into the size given. Extras are dropped'); + assert.deepEqual(_.chunk(a, 2), [[0,1],[2,3]], 'should chunk into the size given'); + assert.deepEqual(_.chunk(b, 2), [[0,1],[2,3]], 'should chunk into the size given. Extras are dropped'); var result = _.chunk(a, 2); - deepEqual(a, _.range(4), 'should not modify the original array'); + assert.deepEqual(a, _.range(4), 'should not modify the original array'); - deepEqual(_.chunk(c, 3, [7,8]), [[0,1,2],[3,4,5],[6,7,8]], 'should allow one to specify a padding array'); - deepEqual(_.chunk(b, 3, 9), [[0,1,2],[3,4,9]], 'should allow one to specify a padding value'); + assert.deepEqual(_.chunk(c, 3, [7,8]), [[0,1,2],[3,4,5],[6,7,8]], 'should allow one to specify a padding array'); + assert.deepEqual(_.chunk(b, 3, 9), [[0,1,2],[3,4,9]], 'should allow one to specify a padding value'); }); - test("chunkAll", function() { + QUnit.test("chunkAll", function(assert) { var a = _.range(4); var b = _.range(10); - deepEqual(_.chunkAll(a, 2), [[0,1],[2,3]], 'should chunk into the size given'); - deepEqual(_.chunkAll(b, 4), [[0,1,2,3],[4,5,6,7],[8,9]], 'should chunk into the size given, with a small end'); + assert.deepEqual(_.chunkAll(a, 2), [[0,1],[2,3]], 'should chunk into the size given'); + assert.deepEqual(_.chunkAll(b, 4), [[0,1,2,3],[4,5,6,7],[8,9]], 'should chunk into the size given, with a small end'); var result = _.chunkAll(a, 2); - deepEqual(a, _.range(4), 'should not modify the original array'); + assert.deepEqual(a, _.range(4), 'should not modify the original array'); - deepEqual(_.chunkAll(b, 2, 4), [[0,1],[4,5],[8,9]], 'should chunk into the size given, with skips'); - deepEqual(_.chunkAll(b, 3, 4), [[0,1,2],[4,5,6],[8,9]], 'should chunk into the size given, with skips and a small end'); + assert.deepEqual(_.chunkAll(b, 2, 4), [[0,1],[4,5],[8,9]], 'should chunk into the size given, with skips'); + assert.deepEqual(_.chunkAll(b, 3, 4), [[0,1,2],[4,5,6],[8,9]], 'should chunk into the size given, with skips and a small end'); }); - test("mapcat", function() { + QUnit.test("mapcat", function(assert) { var a = [1,2,3]; var commaize = function(e) { return _.cons(e, [","]); }; - deepEqual(_.mapcat(a, commaize), [1, ",", 2, ",", 3, ","], 'should return an array with all intermediate mapped arrays concatenated'); + assert.deepEqual(_.mapcat(a, commaize), [1, ",", 2, ",", 3, ","], 'should return an array with all intermediate mapped arrays concatenated'); }); - test("interpose", function() { + QUnit.test("interpose", function(assert) { var a = [1,2,3]; var b = [1,2]; var c = [1]; - deepEqual(_.interpose(a, 0), [1,0,2,0,3], 'should put the 2nd arg between the elements of the array given'); - deepEqual(_.interpose(b, 0), [1,0,2], 'should put the 2nd arg between the elements of the array given'); - deepEqual(_.interpose(c, 0), [1], 'should return the array given if nothing to interpose'); - deepEqual(_.interpose([], 0), [], 'should return an empty array given an empty array'); + assert.deepEqual(_.interpose(a, 0), [1,0,2,0,3], 'should put the 2nd arg between the elements of the array given'); + assert.deepEqual(_.interpose(b, 0), [1,0,2], 'should put the 2nd arg between the elements of the array given'); + assert.deepEqual(_.interpose(c, 0), [1], 'should return the array given if nothing to interpose'); + assert.deepEqual(_.interpose([], 0), [], 'should return an empty array given an empty array'); var result = _.interpose(b,0); - deepEqual(b, [1,2], 'should not modify the original array'); + assert.deepEqual(b, [1,2], 'should not modify the original array'); }); - test("weave", function() { + QUnit.test("weave", function(assert) { var a = [1,2,3]; var b = [1,2]; var c = ['a', 'b', 'c']; var d = [1, [2]]; // zero - deepEqual(_.weave(), [], 'should weave zero arrays'); + assert.deepEqual(_.weave(), [], 'should weave zero arrays'); // one - deepEqual(_.weave([]), [], 'should weave one array'); - deepEqual(_.weave([1,[2]]), [1,[2]], 'should weave one array'); + assert.deepEqual(_.weave([]), [], 'should weave one array'); + assert.deepEqual(_.weave([1,[2]]), [1,[2]], 'should weave one array'); // two - deepEqual(_.weave(a,b), [1,1,2,2,3], 'should weave two arrays'); - deepEqual(_.weave(a,a), [1,1,2,2,3,3], 'should weave two arrays'); - deepEqual(_.weave(c,a), ['a',1,'b',2,'c',3], 'should weave two arrays'); - deepEqual(_.weave(a,d), [1,1,2,[2],3], 'should weave two arrays'); + assert.deepEqual(_.weave(a,b), [1,1,2,2,3], 'should weave two arrays'); + assert.deepEqual(_.weave(a,a), [1,1,2,2,3,3], 'should weave two arrays'); + assert.deepEqual(_.weave(c,a), ['a',1,'b',2,'c',3], 'should weave two arrays'); + assert.deepEqual(_.weave(a,d), [1,1,2,[2],3], 'should weave two arrays'); // > 2 - deepEqual(_.weave(a,b,c), [1,1,'a',2,2,'b',3,'c'], 'should weave more than two arrays'); - deepEqual(_.weave(a,b,c,d), [1,1,'a',1,2,2,'b',[2],3,'c'], 'should weave more than two arrays'); + assert.deepEqual(_.weave(a,b,c), [1,1,'a',2,2,'b',3,'c'], 'should weave more than two arrays'); + assert.deepEqual(_.weave(a,b,c,d), [1,1,'a',1,2,2,'b',[2],3,'c'], 'should weave more than two arrays'); }); - test("repeat", function() { - deepEqual(_.repeat(3,1), [1,1,1], 'should build an array of size n with the specified element in each slot'); - deepEqual(_.repeat(0), [], 'should return an empty array if given zero and no repeat arg'); - deepEqual(_.repeat(0,9999), [], 'should return an empty array if given zero and some repeat arg'); + QUnit.test("repeat", function(assert) { + assert.deepEqual(_.repeat(3,1), [1,1,1], 'should build an array of size n with the specified element in each slot'); + assert.deepEqual(_.repeat(0), [], 'should return an empty array if given zero and no repeat arg'); + assert.deepEqual(_.repeat(0,9999), [], 'should return an empty array if given zero and some repeat arg'); }); - test("cycle", function() { + QUnit.test("cycle", function(assert) { var a = [1,2,3]; - deepEqual(_.cycle(3, a), [1,2,3,1,2,3,1,2,3], 'should build an array with the specified array contents repeated n times'); - deepEqual(_.cycle(0, a), [], 'should return an empty array if told to repeat zero times'); - deepEqual(_.cycle(-1000, a), [], 'should return an empty array if told to repeat negative times'); + assert.deepEqual(_.cycle(3, a), [1,2,3,1,2,3,1,2,3], 'should build an array with the specified array contents repeated n times'); + assert.deepEqual(_.cycle(0, a), [], 'should return an empty array if told to repeat zero times'); + assert.deepEqual(_.cycle(-1000, a), [], 'should return an empty array if told to repeat negative times'); }); - test("splitAt", function() { + QUnit.test("splitAt", function(assert) { var a = [1,2,3,4,5]; - deepEqual(_.splitAt(a, 2), [[1,2],[3,4,5]], 'should bifurcate an array at a given index'); - deepEqual(_.splitAt(a, 0), [[], [1,2,3,4,5]], 'should bifurcate an array at a given index'); - deepEqual(_.splitAt(a, 5), [[1,2,3,4,5],[]], 'should bifurcate an array at a given index'); - deepEqual(_.splitAt([], 5), [[],[]], 'should bifurcate an array at a given index'); + assert.deepEqual(_.splitAt(a, 2), [[1,2],[3,4,5]], 'should bifurcate an array at a given index'); + assert.deepEqual(_.splitAt(a, 0), [[], [1,2,3,4,5]], 'should bifurcate an array at a given index'); + assert.deepEqual(_.splitAt(a, 5), [[1,2,3,4,5],[]], 'should bifurcate an array at a given index'); + assert.deepEqual(_.splitAt([], 5), [[],[]], 'should bifurcate an array at a given index'); }); - test("iterateUntil", function() { + QUnit.test("iterateUntil", function(assert) { var dec = function(n) { return n - 1; }; var isPos = function(n) { return n > 0; }; - deepEqual(_.iterateUntil(dec, isPos, 6), [5,4,3,2,1], 'should build an array, decrementing a number while positive'); + assert.deepEqual(_.iterateUntil(dec, isPos, 6), [5,4,3,2,1], 'should build an array, decrementing a number while positive'); }); - test("takeSkipping", function() { - deepEqual(_.takeSkipping(_.range(5), 0), [], 'should take nothing if told to skip by zero'); - deepEqual(_.takeSkipping(_.range(5), -1), [], 'should take nothing if told to skip by negative'); - deepEqual(_.takeSkipping(_.range(5), 100), [0], 'should take first element if told to skip by big number'); - deepEqual(_.takeSkipping(_.range(5), 1), [0,1,2,3,4], 'should take every element in an array'); - deepEqual(_.takeSkipping(_.range(10), 2), [0,2,4,6,8], 'should take every 2nd element in an array'); + QUnit.test("takeSkipping", function(assert) { + assert.deepEqual(_.takeSkipping(_.range(5), 0), [], 'should take nothing if told to skip by zero'); + assert.deepEqual(_.takeSkipping(_.range(5), -1), [], 'should take nothing if told to skip by negative'); + assert.deepEqual(_.takeSkipping(_.range(5), 100), [0], 'should take first element if told to skip by big number'); + assert.deepEqual(_.takeSkipping(_.range(5), 1), [0,1,2,3,4], 'should take every element in an array'); + assert.deepEqual(_.takeSkipping(_.range(10), 2), [0,2,4,6,8], 'should take every 2nd element in an array'); }); - test("reductions", function() { + QUnit.test("reductions", function(assert) { var result = _.reductions([1,2,3,4,5], function(agg, n) { return agg + n; }, 0); - deepEqual(result, [1,3,6,10,15], 'should retain each intermediate step in a reduce'); + assert.deepEqual(result, [1,3,6,10,15], 'should retain each intermediate step in a reduce'); }); - test("keepIndexed", function() { + QUnit.test("keepIndexed", function(assert) { var a = ['a', 'b', 'c', 'd', 'e']; var b = [-9, 0, 29, -7, 45, 3, -8]; var oddy = function(k, v) { return _.isOdd(k) ? v : undefined; }; var posy = function(k, v) { return _.isPositive(v) ? k : undefined; }; - deepEqual(_.keepIndexed(a, _.isOdd), [false,true,false,true,false], 'runs the predciate on the index, and not the element'); + assert.deepEqual(_.keepIndexed(a, _.isOdd), [false,true,false,true,false], 'runs the predciate on the index, and not the element'); - deepEqual(_.keepIndexed(a, oddy), ['b', 'd'], 'keeps elements whose index passes a truthy test'); - deepEqual(_.keepIndexed(b, posy), [2,4,5], 'keeps elements whose index passes a truthy test'); - deepEqual(_.keepIndexed(_.range(10), oddy), [1,3,5,7,9], 'keeps elements whose index passes a truthy test'); + assert.deepEqual(_.keepIndexed(a, oddy), ['b', 'd'], 'keeps elements whose index passes a truthy test'); + assert.deepEqual(_.keepIndexed(b, posy), [2,4,5], 'keeps elements whose index passes a truthy test'); + assert.deepEqual(_.keepIndexed(_.range(10), oddy), [1,3,5,7,9], 'keeps elements whose index passes a truthy test'); }); - test('reverseOrder', function() { + QUnit.test('reverseOrder', function(assert) { var arr = [1, 2, 3]; - deepEqual(_.reverseOrder(arr), [3, 2, 1], 'returns an array whose elements are in the opposite order of the argument'); - deepEqual(arr, [1, 2, 3], 'should not mutate the argument'); + assert.deepEqual(_.reverseOrder(arr), [3, 2, 1], 'returns an array whose elements are in the opposite order of the argument'); + assert.deepEqual(arr, [1, 2, 3], 'should not mutate the argument'); var throwingFn = function() { _.reverseOrder('string'); }; - throws(throwingFn, TypeError, 'throws a TypeError when given a string'); + assert.throws(throwingFn, TypeError, 'throws a TypeError when given a string'); var argObj = (function() { return arguments; })(1, 2, 3); - deepEqual(_.reverseOrder(argObj), [3, 2, 1], 'works with other array-like objects'); + assert.deepEqual(_.reverseOrder(argObj), [3, 2, 1], 'works with other array-like objects'); }); - test('combinations', function(){ - deepEqual(_.combinations([1]),[[1]],'single array will merely be wrapped'); - deepEqual(_.combinations([1],[2],[3]),[[1,2,3]],'arrays with single elements will merely be merged'); + QUnit.test('combinations', function(assert){ + assert.deepEqual(_.combinations([1]),[[1]],'single array will merely be wrapped'); + assert.deepEqual(_.combinations([1],[2],[3]),[[1,2,3]],'arrays with single elements will merely be merged'); var arr1 = [1,2], arr2 = [3,4,5], arr3 = [6,7], expected = [[1,3,6],[1,3,7],[1,4,6],[1,4,7],[1,5,6],[1,5,7],[2,3,6],[2,3,7],[2,4,6],[2,4,7],[2,5,6],[2,5,7]]; - deepEqual(_.combinations(arr1,arr2,arr3),expected,'array with all possible combinations is returned'); + assert.deepEqual(_.combinations(arr1,arr2,arr3),expected,'array with all possible combinations is returned'); - deepEqual(_.combinations(["a",["b"]],[[1]]),[["a",[1]],[["b"],[1]]],'initial arrays can contain array elements which are then preserved'); + assert.deepEqual(_.combinations(["a",["b"]],[[1]]),[["a",[1]],[["b"],[1]]],'initial arrays can contain array elements which are then preserved'); }); - test('insert', function(){ + QUnit.test('insert', function(assert){ var throwingFn = function() { _.insert({}, 0, 1); }; - throws(throwingFn, TypeError, 'throws a TypeError when passing an object literal'); - - deepEqual(_.insert([], 0, 1), [1],'inserts item in empty array'); - deepEqual(_.insert([2], 0, 1), [1,2],'inserst item at the corret index'); - deepEqual(_.insert([1,2], 2, 3), [1,2,3],'inserts item at the end of array if exceeding index'); - deepEqual(_.insert([1,3], -1, 2), [1,2,3],'inserst item at the correct index if negative index'); + assert.throws(throwingFn, TypeError, 'throws a TypeError when passing an object literal'); + + assert.deepEqual(_.insert([], 0, 1), [1],'inserts item in empty array'); + assert.deepEqual(_.insert([2], 0, 1), [1,2],'inserst item at the corret index'); + assert.deepEqual(_.insert([1,2], 2, 3), [1,2,3],'inserts item at the end of array if exceeding index'); + assert.deepEqual(_.insert([1,3], -1, 2), [1,2,3],'inserst item at the correct index if negative index'); }); }); diff --git a/test/array.selectors.js b/test/array.selectors.js index ac2097a..f88d029 100644 --- a/test/array.selectors.js +++ b/test/array.selectors.js @@ -1,105 +1,105 @@ $(document).ready(function() { - module("underscore.array.selectors"); + QUnit.module("underscore.array.selectors"); - test("second", function() { + QUnit.test("second", function(assert) { var a = [1,2,3,4,5]; - equal(_.second(a), 2, 'should retrieve the 2nd element in an array'); - deepEqual(_.second(a, 5), [2,3,4,5], 'should retrieve all but the first element in an array'); - deepEqual(_.map([a,_.rest(a)], _.second), [2,3], 'should be usable in _.map'); + assert.equal(_.second(a), 2, 'should retrieve the 2nd element in an array'); + assert.deepEqual(_.second(a, 5), [2,3,4,5], 'should retrieve all but the first element in an array'); + assert.deepEqual(_.map([a,_.rest(a)], _.second), [2,3], 'should be usable in _.map'); }); - test("third", function() { + QUnit.test("third", function(assert) { var a = [1,2,3,4,5]; - equal(_.third(a), 3, 'should retrieve the 3rd element in an array'); - deepEqual(_.third(a, 5), [3,4,5], 'should retrieve all but the first and second element in an array'); - deepEqual(_.map([a,_.rest(a)], _.third), [3,4], 'should be usable in _.map'); + assert.equal(_.third(a), 3, 'should retrieve the 3rd element in an array'); + assert.deepEqual(_.third(a, 5), [3,4,5], 'should retrieve all but the first and second element in an array'); + assert.deepEqual(_.map([a,_.rest(a)], _.third), [3,4], 'should be usable in _.map'); }); - test("takeWhile", function() { + QUnit.test("takeWhile", function(assert) { var isNeg = function(n) { return n < 0; }; - deepEqual(_.takeWhile([-2,-1,0,1,2], isNeg), [-2,-1], 'should take elements until a function goes truthy'); - deepEqual(_.takeWhile([1,-2,-1,0,1,2], isNeg), [], 'should take elements until a function goes truthy'); + assert.deepEqual(_.takeWhile([-2,-1,0,1,2], isNeg), [-2,-1], 'should take elements until a function goes truthy'); + assert.deepEqual(_.takeWhile([1,-2,-1,0,1,2], isNeg), [], 'should take elements until a function goes truthy'); }); - test("dropWhile", function() { + QUnit.test("dropWhile", function(assert) { var isNeg = function(n) { return n < 0; }; - deepEqual(_.dropWhile([-2,-1,0,1,2], isNeg), [0,1,2], 'should drop elements until a function goes truthy'); - deepEqual(_.dropWhile([0,1,2], isNeg), [0,1,2], 'should drop elements until a function goes truthy'); - deepEqual(_.dropWhile([-2,-1], isNeg), [], 'should drop elements until a function goes truthy'); - deepEqual(_.dropWhile([1,-2,-1,0,1,2], isNeg), [1,-2,-1,0,1,2], 'should take elements until a function goes truthy'); - deepEqual(_.dropWhile([], isNeg), [], 'should handle empty arrays'); + assert.deepEqual(_.dropWhile([-2,-1,0,1,2], isNeg), [0,1,2], 'should drop elements until a function goes truthy'); + assert.deepEqual(_.dropWhile([0,1,2], isNeg), [0,1,2], 'should drop elements until a function goes truthy'); + assert.deepEqual(_.dropWhile([-2,-1], isNeg), [], 'should drop elements until a function goes truthy'); + assert.deepEqual(_.dropWhile([1,-2,-1,0,1,2], isNeg), [1,-2,-1,0,1,2], 'should take elements until a function goes truthy'); + assert.deepEqual(_.dropWhile([], isNeg), [], 'should handle empty arrays'); }); - test("splitWith", function() { + QUnit.test("splitWith", function(assert) { var a = [1,2,3,4,5]; var lessEq3p = function(n) { return n <= 3; }; var lessEq3p$ = function(n) { return (n <= 3) ? true : null; }; - deepEqual(_.splitWith(a, lessEq3p), [[1,2,3], [4,5]], 'should split an array when a function goes false'); - deepEqual(_.splitWith(a, lessEq3p$), [[1,2,3], [4,5]], 'should split an array when a function goes false'); - deepEqual(_.splitWith([], lessEq3p$), [[],[]], 'should split an empty array into two empty arrays'); + assert.deepEqual(_.splitWith(a, lessEq3p), [[1,2,3], [4,5]], 'should split an array when a function goes false'); + assert.deepEqual(_.splitWith(a, lessEq3p$), [[1,2,3], [4,5]], 'should split an array when a function goes false'); + assert.deepEqual(_.splitWith([], lessEq3p$), [[],[]], 'should split an empty array into two empty arrays'); }); - test("partitionBy", function() { + QUnit.test("partitionBy", function(assert) { var a = [1, 2, null, false, undefined, 3, 4]; - deepEqual(_.partitionBy(a, _.truthy), [[1,2], [null, false, undefined], [3,4]], 'should partition an array as a given predicate changes truth sense'); + assert.deepEqual(_.partitionBy(a, _.truthy), [[1,2], [null, false, undefined], [3,4]], 'should partition an array as a given predicate changes truth sense'); }); - test("best", function() { + QUnit.test("best", function(assert) { var a = [1,2,3,4,5]; - deepEqual(_.best(a, function(x,y) { return x > y; }), 5, 'should identify the best value based on criteria'); + assert.deepEqual(_.best(a, function(x,y) { return x > y; }), 5, 'should identify the best value based on criteria'); }); - test("keep", function() { + QUnit.test("keep", function(assert) { var a = _.range(10); var eveny = function(e) { return (_.isEven(e)) ? e : undefined; }; - deepEqual(_.keep(a, eveny), [0,2,4,6,8], 'should keep only even numbers in a range tagged with null fails'); - deepEqual(_.keep(a, _.isEven), [true, false, true, false, true, false, true, false, true, false], 'should keep all existy values corresponding to a predicate over a range'); + assert.deepEqual(_.keep(a, eveny), [0,2,4,6,8], 'should keep only even numbers in a range tagged with null fails'); + assert.deepEqual(_.keep(a, _.isEven), [true, false, true, false, true, false, true, false, true, false], 'should keep all existy values corresponding to a predicate over a range'); }); - test("nth", function() { + QUnit.test("nth", function(assert) { var a = ['a','b','c']; var b = [['a'],['b'],[]]; - equal(_.nth(a,0), 'a', 'should return the element at a given index into an array'); - equal(_.nth(a,100), undefined, 'should return undefined if out of bounds'); - deepEqual(_.map(b,function(e) { return _.nth(e,0); }), ['a','b',undefined], 'should be usable in _.map'); + assert.equal(_.nth(a,0), 'a', 'should return the element at a given index into an array'); + assert.equal(_.nth(a,100), undefined, 'should return undefined if out of bounds'); + assert.deepEqual(_.map(b,function(e) { return _.nth(e,0); }), ['a','b',undefined], 'should be usable in _.map'); }); - test("nths", function() { + QUnit.test("nths", function(assert) { var a = ['a','b','c', 'd']; - deepEqual(_.nths(a,1), ['b'], 'should return the element at a given index into an array'); - deepEqual(_.nths(a,1,3), ['b', 'd'], 'should return the elements at given indices into an array'); - deepEqual(_.nths(a,1,5,3), ['b', undefined, 'd'], 'should return undefined if out of bounds'); + assert.deepEqual(_.nths(a,1), ['b'], 'should return the element at a given index into an array'); + assert.deepEqual(_.nths(a,1,3), ['b', 'd'], 'should return the elements at given indices into an array'); + assert.deepEqual(_.nths(a,1,5,3), ['b', undefined, 'd'], 'should return undefined if out of bounds'); - deepEqual(_.nths(a,[1]), ['b'], 'should return the element at a given index into an array'); - deepEqual(_.nths(a,[1,3]), ['b', 'd'], 'should return the elements at given indices into an array'); - deepEqual(_.nths(a,[1,5,3]), ['b', undefined, 'd'], 'should return undefined if out of bounds'); + assert.deepEqual(_.nths(a,[1]), ['b'], 'should return the element at a given index into an array'); + assert.deepEqual(_.nths(a,[1,3]), ['b', 'd'], 'should return the elements at given indices into an array'); + assert.deepEqual(_.nths(a,[1,5,3]), ['b', undefined, 'd'], 'should return undefined if out of bounds'); }); - test("valuesAt", function() { - equal(_.valuesAt, _.nths, 'valuesAt should be alias for nths'); + QUnit.test("valuesAt", function(assert) { + assert.equal(_.valuesAt, _.nths, 'valuesAt should be alias for nths'); }); - test("binPick", function() { + QUnit.test("binPick", function(assert) { var a = ['a','b','c', 'd']; - deepEqual(_.binPick(a, false, true), ['b'], 'should return the element at a given index into an array'); - deepEqual(_.binPick(a, false, true, false, true), ['b', 'd'], 'should return the elements at given indices into an array'); - deepEqual(_.binPick(a, false, true, false, true, true), ['b', 'd', undefined], 'should return undefined if out of bounds'); + assert.deepEqual(_.binPick(a, false, true), ['b'], 'should return the element at a given index into an array'); + assert.deepEqual(_.binPick(a, false, true, false, true), ['b', 'd'], 'should return the elements at given indices into an array'); + assert.deepEqual(_.binPick(a, false, true, false, true, true), ['b', 'd', undefined], 'should return undefined if out of bounds'); - deepEqual(_.binPick(a, [false, true]), ['b'], 'should return the element at a given index into an array'); - deepEqual(_.binPick(a, [false, true, false, true]), ['b', 'd'], 'should return the elements at given indices into an array'); - deepEqual(_.binPick(a, [false, true, false, true, true]), ['b', 'd', undefined], 'should return undefined if out of bounds'); + assert.deepEqual(_.binPick(a, [false, true]), ['b'], 'should return the element at a given index into an array'); + assert.deepEqual(_.binPick(a, [false, true, false, true]), ['b', 'd'], 'should return the elements at given indices into an array'); + assert.deepEqual(_.binPick(a, [false, true, false, true, true]), ['b', 'd', undefined], 'should return undefined if out of bounds'); }); }); diff --git a/test/collections.walk.js b/test/collections.walk.js index 4e7ea04..7f16bb7 100644 --- a/test/collections.walk.js +++ b/test/collections.walk.js @@ -1,6 +1,6 @@ $(document).ready(function() { - module("underscore.collections.walk"); + QUnit.module("underscore.collections.walk"); var getSimpleTestTree = function() { return { @@ -21,7 +21,11 @@ $(document).ready(function() { }; }; - test("basic", function() { + var getArrayValues = function() { + return ["a", "a", "a", "a", "b", "c", "d", "e" ]; + }; + + QUnit.test("basic", function(assert) { // Updates the value of `node` to be the sum of the values of its subtrees. // Ignores leaf nodes. var visitor = function(node) { @@ -31,106 +35,106 @@ $(document).ready(function() { var tree = getSimpleTestTree(); _.walk.postorder(tree, visitor); - equal(tree.val, 16, 'should visit subtrees first'); - + assert.equal(tree.val, 16, 'should visit subtrees first'); + tree = getSimpleTestTree(); _.walk.preorder(tree, visitor); - equal(tree.val, 5, 'should visit subtrees after the node itself'); + assert.equal(tree.val, 5, 'should visit subtrees after the node itself'); }); - - test("circularRefs", function() { + + QUnit.test("circularRefs", function(assert) { var tree = getSimpleTestTree(); tree.l.l.r = tree; - throws(function() { _.walk.preorder(tree, _.identity); }, TypeError, 'preorder throws an exception'); - throws(function() { _.walk.postrder(tree, _.identity); }, TypeError, 'postorder throws an exception'); + assert.throws(function() { _.walk.preorder(tree, _.identity); }, TypeError, 'preorder throws an exception'); + assert.throws(function() { _.walk.postrder(tree, _.identity); }, TypeError, 'postorder throws an exception'); tree = getSimpleTestTree(); tree.r.l = tree.r; - throws(function() { _.walk.preorder(tree, _.identity); }, TypeError, 'exception for a self-referencing node'); + assert.throws(function() { _.walk.preorder(tree, _.identity); }, TypeError, 'exception for a self-referencing node'); }); - test("simpleMap", function() { + QUnit.test("simpleMap", function(assert) { var visitor = function(node, key, parent) { if (_.has(node, 'val')) return node.val; if (key !== 'val') throw new Error('Leaf node with incorrect key'); return this.leafChar || '-'; }; var visited = _.walk.map(getSimpleTestTree(), _.walk.preorder, visitor).join(''); - equal(visited, '0-1-2-3-4-5-6-', 'pre-order map'); + assert.equal(visited, '0-1-2-3-4-5-6-', 'pre-order map'); visited = _.walk.map(getSimpleTestTree(), _.walk.postorder, visitor).join(''); - equal(visited, '---2-31--5-640', 'post-order map'); + assert.equal(visited, '---2-31--5-640', 'post-order map'); var context = { leafChar: '*' }; visited = _.walk.map(getSimpleTestTree(), _.walk.preorder, visitor, context).join(''); - equal(visited, '0*1*2*3*4*5*6*', 'pre-order with context'); + assert.equal(visited, '0*1*2*3*4*5*6*', 'pre-order with context'); visited = _.walk.map(getSimpleTestTree(), _.walk.postorder, visitor, context).join(''); - equal(visited, '***2*31**5*640', 'post-order with context'); + assert.equal(visited, '***2*31**5*640', 'post-order with context'); if (document.querySelector) { var root = document.querySelector('#map-test'); var ids = _.walk.map(root, _.walk.preorder, function(el) { return el.id; }); - deepEqual(ids, ['map-test', 'id1', 'id2'], 'preorder map with DOM elements'); + assert.deepEqual(ids, ['map-test', 'id1', 'id2'], 'preorder map with DOM elements'); ids = _.walk.map(root, _.walk.postorder, function(el) { return el.id; }); - deepEqual(ids, ['id1', 'id2', 'map-test'], 'postorder map with DOM elements'); + assert.deepEqual(ids, ['id1', 'id2', 'map-test'], 'postorder map with DOM elements'); } }); - test("mixedMap", function() { + QUnit.test("mixedMap", function(assert) { var visitor = function(node, key, parent) { return _.isString(node) ? node.toLowerCase() : null; }; var tree = getMixedTestTree(); var preorderResult = _.walk.map(tree, _.walk.preorder, visitor); - equal(preorderResult.length, 19, 'all nodes are visited'); - deepEqual(_.reject(preorderResult, _.isNull), + assert.equal(preorderResult.length, 19, 'all nodes are visited'); + assert.deepEqual(_.reject(preorderResult, _.isNull), ['munich', 'muenchen', 'san francisco', 'sf', 'san fran', 'toronto', 'to', 't-dot'], 'pre-order map on a mixed tree'); var postorderResult = _.walk.map(tree, _.walk.postorder, visitor); - deepEqual(preorderResult.sort(), postorderResult.sort(), 'post-order map on a mixed tree'); + assert.deepEqual(preorderResult.sort(), postorderResult.sort(), 'post-order map on a mixed tree'); tree = [['foo'], tree]; var result = _.walk.map(tree, _.walk.postorder, visitor); - deepEqual(_.difference(result, postorderResult), ['foo'], 'map on list of trees'); + assert.deepEqual(_.difference(result, postorderResult), ['foo'], 'map on list of trees'); }); - test("pluck", function() { + QUnit.test("pluck", function(assert) { var tree = getSimpleTestTree(); tree.val = { val: 'z' }; var plucked = _.walk.pluckRec(tree, 'val'); - equal(plucked.shift(), tree.val); - equal(plucked.join(''), 'z123456', 'pluckRec is recursive'); + assert.equal(plucked.shift(), tree.val); + assert.equal(plucked.join(''), 'z123456', 'pluckRec is recursive'); plucked = _.walk.pluck(tree, 'val'); - equal(plucked.shift(), tree.val); - equal(plucked.join(''), '123456', 'regular pluck is not recursive'); + assert.equal(plucked.shift(), tree.val); + assert.equal(plucked.join(''), '123456', 'regular pluck is not recursive'); tree.l.r.foo = 42; - equal(_.walk.pluck(tree, 'foo'), 42, 'pluck a value from deep in the tree'); + assert.equal(_.walk.pluck(tree, 'foo'), 42, 'pluck a value from deep in the tree'); tree = getMixedTestTree(); - deepEqual(_.walk.pluck(tree, 'city'), ['Munich', 'San Francisco', 'Toronto'], 'pluck from a mixed tree'); + assert.deepEqual(_.walk.pluck(tree, 'city'), ['Munich', 'San Francisco', 'Toronto'], 'pluck from a mixed tree'); tree = [tree, { city: 'Loserville', population: 'you' }]; - deepEqual(_.walk.pluck(tree, 'population'), [1378000, 812826, 2615000, 'you'], 'pluck from a list of trees'); + assert.deepEqual(_.walk.pluck(tree, 'population'), [1378000, 812826, 2615000, 'you'], 'pluck from a list of trees'); }); - test("reduce", function() { + QUnit.test("reduce", function(assert) { var add = function(a, b) { return a + b; }; var leafMemo = []; var sum = function(memo, node) { if (_.isObject(node)) return _.reduce(memo, add, 0); - strictEqual(memo, leafMemo); + assert.strictEqual(memo, leafMemo); return node; }; var tree = getSimpleTestTree(); - equal(_.walk.reduce(tree, sum, leafMemo), 21); + assert.equal(_.walk.reduce(tree, sum, leafMemo), 21); // A more useful example: transforming a tree. @@ -143,11 +147,11 @@ $(document).ready(function() { var toString = function(node) { return _.has(node, 'val') ? '-' : node; }; tree = _.walk.reduce(getSimpleTestTree(), mirror); - equal(_.walk.reduce(tree, sum, leafMemo), 21); - equal(_.walk.map(tree, _.walk.preorder, toString).join(''), '-0-4-6-5-1-3-2', 'pre-order map'); + assert.equal(_.walk.reduce(tree, sum, leafMemo), 21); + assert.equal(_.walk.map(tree, _.walk.preorder, toString).join(''), '-0-4-6-5-1-3-2', 'pre-order map'); }); - test("find", function() { + QUnit.test("find", function(assert) { var tree = getSimpleTestTree(); // Returns a visitor function that will succeed when a node with the given @@ -161,40 +165,40 @@ $(document).ready(function() { }; }; - equal(_.walk.find(tree, findValue(0)).val, 0); - equal(_.walk.find(tree, findValue(6)).val, 6); - deepEqual(_.walk.find(tree, findValue(99)), undefined); + assert.equal(_.walk.find(tree, findValue(0)).val, 0); + assert.equal(_.walk.find(tree, findValue(6)).val, 6); + assert.deepEqual(_.walk.find(tree, findValue(99)), undefined); }); - test("filter", function() { + QUnit.test("filter", function(assert) { var tree = getSimpleTestTree(); tree.r.val = '.oOo.'; // Remove one of the numbers. var isEvenNumber = function(x) { return _.isNumber(x) && x % 2 === 0; }; - equal(_.walk.filter(tree, _.walk.preorder, _.isObject).length, 7, 'filter objects'); - equal(_.walk.filter(tree, _.walk.preorder, _.isNumber).length, 6, 'filter numbers'); - equal(_.walk.filter(tree, _.walk.postorder, _.isNumber).length, 6, 'postorder filter numbers'); - equal(_.walk.filter(tree, _.walk.preorder, isEvenNumber).length, 3, 'filter even numbers'); + assert.equal(_.walk.filter(tree, _.walk.preorder, _.isObject).length, 7, 'filter objects'); + assert.equal(_.walk.filter(tree, _.walk.preorder, _.isNumber).length, 6, 'filter numbers'); + assert.equal(_.walk.filter(tree, _.walk.postorder, _.isNumber).length, 6, 'postorder filter numbers'); + assert.equal(_.walk.filter(tree, _.walk.preorder, isEvenNumber).length, 3, 'filter even numbers'); // With the identity function, only the value '0' should be omitted. - equal(_.walk.filter(tree, _.walk.preorder, _.identity).length, 13, 'filter on identity function'); + assert.equal(_.walk.filter(tree, _.walk.preorder, _.identity).length, 13, 'filter on identity function'); }); - test("reject", function() { + QUnit.test("reject", function(assert) { var tree = getSimpleTestTree(); tree.r.val = '.oOo.'; // Remove one of the numbers. - equal(_.walk.reject(tree, _.walk.preorder, _.isObject).length, 7, 'reject objects'); - equal(_.walk.reject(tree, _.walk.preorder, _.isNumber).length, 8, 'reject numbers'); - equal(_.walk.reject(tree, _.walk.postorder, _.isNumber).length, 8, 'postorder reject numbers'); + assert.equal(_.walk.reject(tree, _.walk.preorder, _.isObject).length, 7, 'reject objects'); + assert.equal(_.walk.reject(tree, _.walk.preorder, _.isNumber).length, 8, 'reject numbers'); + assert.equal(_.walk.reject(tree, _.walk.postorder, _.isNumber).length, 8, 'postorder reject numbers'); // With the identity function, only the value '0' should be kept. - equal(_.walk.reject(tree, _.walk.preorder, _.identity).length, 1, 'reject with identity function'); + assert.equal(_.walk.reject(tree, _.walk.preorder, _.identity).length, 1, 'reject with identity function'); }); - test("customTraversal", function() { + QUnit.test("customTraversal", function(assert) { var tree = getSimpleTestTree(); // Set up a walker that will not traverse the 'val' properties. @@ -204,13 +208,29 @@ $(document).ready(function() { var visitor = function(node) { if (!_.isObject(node)) throw new Error("Leaf value visited when it shouldn't be"); }; - equal(walker.pluck(tree, 'val').length, 7, 'pluck with custom traversal'); - equal(walker.pluckRec(tree, 'val').length, 7, 'pluckRec with custom traversal'); + assert.equal(walker.pluck(tree, 'val').length, 7, 'pluck with custom traversal'); + assert.equal(walker.pluckRec(tree, 'val').length, 7, 'pluckRec with custom traversal'); - equal(walker.map(tree, _.walk.postorder, _.identity).length, 7, 'traversal strategy is dynamically scoped'); + assert.equal(walker.map(tree, _.walk.postorder, _.identity).length, 7, 'traversal strategy is dynamically scoped'); // Check that the default walker is unaffected. - equal(_.walk.map(tree, _.walk.postorder, _.identity).length, 14, 'default map still works'); - equal(_.walk.pluckRec(tree, 'val').join(''), '0123456', 'default pluckRec still works'); + assert.equal(_.walk.map(tree, _.walk.postorder, _.identity).length, 14, 'default map still works'); + assert.equal(_.walk.pluckRec(tree, 'val').join(''), '0123456', 'default pluckRec still works'); + }); + + QUnit.test("containsAtLeast", function(assert){ + var array = getArrayValues(); + + assert.equal(_.walk.containsAtLeast(array, 3, "a"), true, "list contains at least 3 items"); + assert.equal(_.walk.containsAtLeast(array, 1, "b"), true, "list contains at least 1 items"); + assert.equal(_.walk.containsAtLeast(array, 1, "f"), false, "list doesn't contain item for that value"); + }); + + QUnit.test("containsAtMost", function(assert){ + var array = getArrayValues(); + + assert.equal(_.walk.containsAtMost(array, 4, "a"), true, "list contains at most 4 items"); + assert.equal(_.walk.containsAtMost(array, 1, "b"), true, "list contains at most 1 value"); + assert.equal(_.walk.containsAtMost(array, 1, "f"), true, "list contains at most 1 value"); }); }); diff --git a/test/dist-concat.html b/test/dist-concat.html index 21f6f17..9adb49c 100644 --- a/test/dist-concat.html +++ b/test/dist-concat.html @@ -1,13 +1,13 @@ - + Underscore-contrib Test Suite - - - - - + + + + + diff --git a/test/dist-min.html b/test/dist-min.html index 1527f06..17d1832 100644 --- a/test/dist-min.html +++ b/test/dist-min.html @@ -1,13 +1,13 @@ - + Underscore-contrib Test Suite - - - - - + + + + + diff --git a/test/function.arity.js b/test/function.arity.js index 31531a0..e4cbbb9 100644 --- a/test/function.arity.js +++ b/test/function.arity.js @@ -1,13 +1,13 @@ $(document).ready(function() { - module("underscore.function.arity"); + QUnit.module("underscore.function.arity"); - test("fix", function() { + QUnit.test("fix", function(assert) { var over = function(t, m, b) { return t / m / b; }; var t = _.fix(over, 10, _, _); - equal(t(5, 2), 1, 'should return a function partially applied for some number of arbitrary args marked by _'); - equal(t(10, 2), 0.5, 'should return a function partially applied for some number of arbitrary args marked by _'); - equal(t(10, 5), 0.2, 'should return a function partially applied for some number of arbitrary args marked by _'); + assert.equal(t(5, 2), 1, 'should return a function partially applied for some number of arbitrary args marked by _'); + assert.equal(t(10, 2), 0.5, 'should return a function partially applied for some number of arbitrary args marked by _'); + assert.equal(t(10, 5), 0.2, 'should return a function partially applied for some number of arbitrary args marked by _'); var f = function () { return _.map(arguments, function (arg) { @@ -15,23 +15,23 @@ $(document).ready(function() { }).join(', '); }; var g = _.fix(f, _, _, 3); - equal(g(1), 'number, undefined, number', 'should fill "undefined" if argument not given'); + assert.equal(g(1), 'number, undefined, number', 'should fill "undefined" if argument not given'); g(1, 2); - equal(g(1), 'number, undefined, number', 'should not remember arguments between calls'); + assert.equal(g(1), 'number, undefined, number', 'should not remember arguments between calls'); - equal(_.fix(parseInt, _, 10)('11'), 11, 'should "fix" common js foibles'); + assert.equal(_.fix(parseInt, _, 10)('11'), 11, 'should "fix" common js foibles'); - equal(_.fix(f, _, 3)(1,'a'), 'number, number', 'should ignore extra parameters'); + assert.equal(_.fix(f, _, 3)(1,'a'), 'number, number', 'should ignore extra parameters'); }); - test("arity", function () { + QUnit.test("arity", function(assert) { function variadic () { return arguments.length; } function unvariadic (a, b, c) { return arguments.length; } - equal( _.arity(unvariadic.length, variadic).length, unvariadic.length, "should set the length"); - equal( _.arity(3, variadic)(1, 2, 3, 4, 5), unvariadic(1, 2, 3, 4, 5), "shouldn't trim arguments"); - equal( _.arity(3, variadic)(1), unvariadic(1), "shouldn't pad arguments"); + assert.equal( _.arity(unvariadic.length, variadic).length, unvariadic.length, "should set the length"); + assert.equal( _.arity(3, variadic)(1, 2, 3, 4, 5), unvariadic(1, 2, 3, 4, 5), "shouldn't trim arguments"); + assert.equal( _.arity(3, variadic)(1), unvariadic(1), "shouldn't pad arguments"); // this is the big use case for _.arity: @@ -50,36 +50,36 @@ $(document).ready(function() { function echo (a, b, c) { return [a, b, c]; } - deepEqual(naiveFlip(echo)(1, 2, 3), [3, 2, 1], "naive flip flips its arguments"); - notEqual(naiveFlip(echo).length, echo.length, "naiveFlip gets its arity wrong"); + assert.deepEqual(naiveFlip(echo)(1, 2, 3), [3, 2, 1], "naive flip flips its arguments"); + assert.notEqual(naiveFlip(echo).length, echo.length, "naiveFlip gets its arity wrong"); function flipWithArity (fun) { return _.arity(fun.length, naiveFlip(fun)); } - deepEqual(flipWithArity(echo)(1, 2, 3), [3, 2, 1], "flipWithArity flips its arguments"); - equal(flipWithArity(echo).length, echo.length, "flipWithArity gets its arity correct"); + assert.deepEqual(flipWithArity(echo)(1, 2, 3), [3, 2, 1], "flipWithArity flips its arguments"); + assert.equal(flipWithArity(echo).length, echo.length, "flipWithArity gets its arity correct"); }); - test("curry", function() { + QUnit.test("curry", function(assert) { var func = function (x, y, z) { return x + y + z; }, curried = _.curry(func), rCurried = _.curryRight(func); - equal(func(1, 2, 3), 6, "Test pure function"); - equal(typeof curried, 'function', "Curry returns a function"); - equal(typeof curried(1), 'function', "Curry returns a function after partial application"); - equal(curried(1)(2)(3), 6, "Curry returns a value after total application"); - equal(curried(1)(2)(3), 6, "Curry invocations have no side effects and do not interact with each other"); - equal(curried(2)(4)(8), 14, "Curry invocations have no side effects and do not interact with each other"); - equal(rCurried('a')('b')('c'), 'cba', "Flipped curry applies arguments in reverse."); + assert.equal(func(1, 2, 3), 6, "Test pure function"); + assert.equal(typeof curried, 'function', "Curry returns a function"); + assert.equal(typeof curried(1), 'function', "Curry returns a function after partial application"); + assert.equal(curried(1)(2)(3), 6, "Curry returns a value after total application"); + assert.equal(curried(1)(2)(3), 6, "Curry invocations have no side effects and do not interact with each other"); + assert.equal(curried(2)(4)(8), 14, "Curry invocations have no side effects and do not interact with each other"); + assert.equal(rCurried('a')('b')('c'), 'cba', "Flipped curry applies arguments in reverse."); var addyz = curried(1); - equal(addyz(2)(3), 6, "Partial applications can be used multiple times"); - equal(addyz(2)(4), 7, "Partial applications can be used multiple times"); + assert.equal(addyz(2)(3), 6, "Partial applications can be used multiple times"); + assert.equal(addyz(2)(4), 7, "Partial applications can be used multiple times"); var failure = false; try { @@ -87,47 +87,47 @@ $(document).ready(function() { } catch (e) { failure = true; } finally { - equal(failure, true, "Curried functions only accept one argument at a time"); + assert.equal(failure, true, "Curried functions only accept one argument at a time"); } }); - test("curry2", function () { + QUnit.test("curry2", function(assert) { function echo () { return [].slice.call(arguments, 0); } - deepEqual(echo(1, 2), [1, 2], "Control test"); - deepEqual(_.curry2(echo)(1)(2), [1, 2], "Accepts curried arguments"); + assert.deepEqual(echo(1, 2), [1, 2], "Control test"); + assert.deepEqual(_.curry2(echo)(1)(2), [1, 2], "Accepts curried arguments"); }); - test("curryRight2", function () { + QUnit.test("curryRight2", function(assert) { function echo () { return [].slice.call(arguments, 0); } - deepEqual(echo(1, 2), [1, 2], "Control test"); - deepEqual(_.curryRight2(echo)(1)(2), [2, 1], "Reverses curried arguments"); - equal(_.curryRight2, _.rcurry2, "should have alias 'rcurry2'"); + assert.deepEqual(echo(1, 2), [1, 2], "Control test"); + assert.deepEqual(_.curryRight2(echo)(1)(2), [2, 1], "Reverses curried arguments"); + assert.equal(_.curryRight2, _.rcurry2, "should have alias 'rcurry2'"); }); - test("curry3", function () { + QUnit.test("curry3", function(assert) { function echo () { return [].slice.call(arguments, 0); } - deepEqual(echo(1, 2, 3), [1, 2, 3], "Control test"); - deepEqual(_.curry3(echo)(1)(2)(3), [1, 2, 3], "Accepts curried arguments"); + assert.deepEqual(echo(1, 2, 3), [1, 2, 3], "Control test"); + assert.deepEqual(_.curry3(echo)(1)(2)(3), [1, 2, 3], "Accepts curried arguments"); }); - test("curryRight3", function () { + QUnit.test("curryRight3", function(assert) { function echo () { return [].slice.call(arguments, 0); } - deepEqual(echo(1, 2, 3), [1, 2, 3], "Control test"); - deepEqual(_.curryRight3(echo)(1)(2)(3), [3, 2, 1], "Reverses curried arguments"); - equal(_.curryRight3, _.rcurry3, "should have alias 'rcurry3'"); + assert.deepEqual(echo(1, 2, 3), [1, 2, 3], "Control test"); + assert.deepEqual(_.curryRight3(echo)(1)(2)(3), [3, 2, 1], "Reverses curried arguments"); + assert.equal(_.curryRight3, _.rcurry3, "should have alias 'rcurry3'"); }); - test("enforce", function () { + QUnit.test("enforce", function(assert) { function binary (a, b) { return a + b; } @@ -146,9 +146,9 @@ $(document).ready(function() { } catch (e) { failure = true; } finally { - equal(failure, true, "Binary must have two arguments."); + assert.equal(failure, true, "Binary must have two arguments."); } - equal(fBinary(1, 2), 3, "Function returns after proper application"); + assert.equal(fBinary(1, 2), 3, "Function returns after proper application"); failure = false; try { @@ -156,9 +156,9 @@ $(document).ready(function() { } catch (e) { failure = true; } finally { - equal(failure, true, "Ternary must have three arguments."); + assert.equal(failure, true, "Ternary must have three arguments."); } - equal(fTernary(1, 2, 3), 6, "Function returns after proper application"); - equal(fAltTernary(1, 2, 3), -4, "Function cache does not collide"); + assert.equal(fTernary(1, 2, 3), 6, "Function returns after proper application"); + assert.equal(fAltTernary(1, 2, 3), -4, "Function cache does not collide"); }); }); diff --git a/test/function.combinators.js b/test/function.combinators.js index 35d09fe..d3001e7 100644 --- a/test/function.combinators.js +++ b/test/function.combinators.js @@ -1,52 +1,52 @@ $(document).ready(function() { - module("underscore.function.combinators"); + QUnit.module("underscore.function.combinators"); - test("always", function() { - equal(_.always(42)(10000), 42, 'should return a function that always returns the same value'); - equal(_.always(42)(1,2,3), 42, 'should return a function that always returns the same value'); - deepEqual(_.map([1,2,3], _.always(42)), [42,42,42], 'should return a function that always returns the same value'); + QUnit.test("always", function(assert) { + assert.equal(_.always(42)(10000), 42, 'should return a function that always returns the same value'); + assert.equal(_.always(42)(1,2,3), 42, 'should return a function that always returns the same value'); + assert.deepEqual(_.map([1,2,3], _.always(42)), [42,42,42], 'should return a function that always returns the same value'); }); - test("pipeline", function() { + QUnit.test("pipeline", function(assert) { var run = _.pipeline(function(n) { return -n; }, function(n) { return "" + n; }); var run2 = _.pipeline([function(n) { return -n; }, function(n) { return "" + n; }]); - equal(run(42), "-42", 'should apply a series of functions, originall given variadically to an initial value'); - equal(run2(42), "-42", 'should apply a series of functions, originally given in an array to an initial value'); + assert.equal(run(42), "-42", 'should apply a series of functions, originall given variadically to an initial value'); + assert.equal(run2(42), "-42", 'should apply a series of functions, originally given in an array to an initial value'); }); - test("conjoin", function() { + QUnit.test("conjoin", function(assert) { var isPositiveEven = _.conjoin(function(x) { return x > 0; }, function(x) { return (x & 1) === 0; }); - equal(isPositiveEven(2), true, 'should recognize that element satisfies a conjunction'); - equal(isPositiveEven(1), false, 'should recognize that element does not satisfy a conjunction'); - equal(isPositiveEven([2,4,6,8]), true, 'should recognize when all elements satisfy a conjunction'); - equal(isPositiveEven([2,4,6,7,8]), false, 'should recognize when an element fails to satisfy a conjunction'); + assert.equal(isPositiveEven(2), true, 'should recognize that element satisfies a conjunction'); + assert.equal(isPositiveEven(1), false, 'should recognize that element does not satisfy a conjunction'); + assert.equal(isPositiveEven([2,4,6,8]), true, 'should recognize when all elements satisfy a conjunction'); + assert.equal(isPositiveEven([2,4,6,7,8]), false, 'should recognize when an element fails to satisfy a conjunction'); }); - test("disjoin", function() { + QUnit.test("disjoin", function(assert) { var orPositiveEven = _.disjoin(function(x) { return x > 0; }, function(x) { return (x & 1) === 0; }); - equal(orPositiveEven(2), true, 'should recognize that element satisfies a disjunction'); - equal(orPositiveEven(-1), false, 'should recognize that element does not satisfy a disjunction'); - equal(orPositiveEven([-1,2,3,4,5,6]), true, 'should recognize when all elements satisfy a disjunction'); - equal(orPositiveEven([-1,-3]), false, 'should recognize when an element fails to satisfy a disjunction'); + assert.equal(orPositiveEven(2), true, 'should recognize that element satisfies a disjunction'); + assert.equal(orPositiveEven(-1), false, 'should recognize that element does not satisfy a disjunction'); + assert.equal(orPositiveEven([-1,2,3,4,5,6]), true, 'should recognize when all elements satisfy a disjunction'); + assert.equal(orPositiveEven([-1,-3]), false, 'should recognize when an element fails to satisfy a disjunction'); }); - test("comparator", function() { + QUnit.test("comparator", function(assert) { var lessOrEqual = function(x, y) { return x <= y; }; var a = [0, 1, -2]; var b = [100, 1, 0, 10, -1, -2, -1]; - deepEqual(a.sort(_.comparator(lessOrEqual)), [-2, 0, 1], 'should return a function to convert a predicate to a comparator'); - deepEqual(b.sort(_.comparator(lessOrEqual)), [-2, -1, -1, 0, 1, 10, 100], 'should return a function to convert a predicate to a comparator'); + assert.deepEqual(a.sort(_.comparator(lessOrEqual)), [-2, 0, 1], 'should return a function to convert a predicate to a comparator'); + assert.deepEqual(b.sort(_.comparator(lessOrEqual)), [-2, -1, -1, 0, 1, 10, 100], 'should return a function to convert a predicate to a comparator'); }); - test("complement", function() { + QUnit.test("complement", function(assert) { var notOdd = _.complement(function(n) { return (n & 1) === 1; }); - equal(notOdd(2), true, 'should return a function that is the opposite of the function given'); - equal(notOdd(3), false, 'should return a function that is the opposite of the function given'); + assert.equal(notOdd(2), true, 'should return a function that is the opposite of the function given'); + assert.equal(notOdd(3), false, 'should return a function that is the opposite of the function given'); var obj = { num: 1, @@ -54,17 +54,17 @@ $(document).ready(function() { }; obj.numIsNotPositive = _.complement(obj.numIsPositive); - equal(obj.numIsNotPositive(), false, 'should function as a method combinator'); + assert.equal(obj.numIsNotPositive(), false, 'should function as a method combinator'); }); - test('splat', function() { + QUnit.test('splat', function(assert) { var sumArgs = function () { return _.reduce(arguments, function (a, b) { return a + b; }, 0); }; var sumArray = _.splat(sumArgs); - equal(sumArray([1, 2, 3]), 6, 'should return a function that takes array elements as the arguments for the original function'); + assert.equal(sumArray([1, 2, 3]), 6, 'should return a function that takes array elements as the arguments for the original function'); var obj = { a: 1, @@ -79,73 +79,73 @@ $(document).ready(function() { }; obj.getPropsByNameArray = _.splat(obj.getPropsByName); - deepEqual(obj.getPropsByNameArray(['a', 'b']), [1, 2], 'should function as a method combinator'); + assert.deepEqual(obj.getPropsByNameArray(['a', 'b']), [1, 2], 'should function as a method combinator'); }); - test("unsplat", function() { + QUnit.test("unsplat", function(assert) { var echo = _.unsplat(function (args) { return args; }), echo2 = _.unsplat(function (first, rest) { return [first, rest]; }), echo3 = _.unsplat(function (first, second, rest) { return [first, second, rest]; }); - deepEqual(echo(), [], 'should return no arguments'); - deepEqual(echo(1), [1], 'should return the arguments provded'); - deepEqual(echo(1,2), [1,2], 'should return the arguments provded'); - deepEqual(echo(1,2,3), [1,2,3], 'should return the arguments provded'); - - deepEqual(echo2(), [void 0, []], 'should return no arguments'); - deepEqual(echo2(1), [1, []], 'should return the arguments provded'); - deepEqual(echo2(1,2), [1,[2]], 'should return the arguments provded'); - deepEqual(echo2(1,2,3), [1,[2,3]], 'should return the arguments provded'); - deepEqual(echo2(1,2,3,4), [1,[2,3,4]], 'should return the arguments provded'); - - deepEqual(echo3(), [void 0, void 0, []], 'should return no arguments'); - deepEqual(echo3(1), [1, void 0, []], 'should return the arguments provded'); - deepEqual(echo3(1,2), [1,2,[]], 'should return the arguments provded'); - deepEqual(echo3(1,2,3), [1,2,[3]], 'should return the arguments provded'); - deepEqual(echo3(1,2,3,4), [1,2,[3,4]], 'should return the arguments provded'); + assert.deepEqual(echo(), [], 'should return no arguments'); + assert.deepEqual(echo(1), [1], 'should return the arguments provded'); + assert.deepEqual(echo(1,2), [1,2], 'should return the arguments provded'); + assert.deepEqual(echo(1,2,3), [1,2,3], 'should return the arguments provded'); + + assert.deepEqual(echo2(), [void 0, []], 'should return no arguments'); + assert.deepEqual(echo2(1), [1, []], 'should return the arguments provded'); + assert.deepEqual(echo2(1,2), [1,[2]], 'should return the arguments provded'); + assert.deepEqual(echo2(1,2,3), [1,[2,3]], 'should return the arguments provded'); + assert.deepEqual(echo2(1,2,3,4), [1,[2,3,4]], 'should return the arguments provded'); + + assert.deepEqual(echo3(), [void 0, void 0, []], 'should return no arguments'); + assert.deepEqual(echo3(1), [1, void 0, []], 'should return the arguments provded'); + assert.deepEqual(echo3(1,2), [1,2,[]], 'should return the arguments provded'); + assert.deepEqual(echo3(1,2,3), [1,2,[3]], 'should return the arguments provded'); + assert.deepEqual(echo3(1,2,3,4), [1,2,[3,4]], 'should return the arguments provded'); }); - test("unsplatl", function() { + QUnit.test("unsplatl", function(assert) { var echo = _.unsplatl(function (args) { return args; }), echo2 = _.unsplatl(function (rest, ultimate) { return [rest, ultimate]; }), echo3 = _.unsplatl(function (rest, penultimate, ultimate) { return [rest, penultimate, ultimate]; }); - deepEqual(echo(), [], 'should return no arguments'); - deepEqual(echo(1), [1], 'should return the arguments provded'); - deepEqual(echo(1,2), [1,2], 'should return the arguments provded'); - deepEqual(echo(1,2,3), [1,2,3], 'should return the arguments provded'); - - deepEqual(echo2(), [[], void 0], 'should return no arguments'); - deepEqual(echo2(1), [[], 1], 'should return the arguments provded'); - deepEqual(echo2(1,2), [[1], 2], 'should return the arguments provded'); - deepEqual(echo2(1,2,3), [[1, 2], 3], 'should return the arguments provded'); - deepEqual(echo2(1,2,3,4), [[1, 2, 3], 4], 'should return the arguments provded'); - - deepEqual(echo3(), [[], void 0, void 0], 'should return no arguments'); - deepEqual(echo3(1), [[], 1, void 0], 'should return the arguments provded'); - deepEqual(echo3(1,2), [[], 1, 2], 'should return the arguments provded'); - deepEqual(echo3(1,2,3), [[1], 2, 3], 'should return the arguments provded'); - deepEqual(echo3(1,2,3,4), [[1, 2], 3, 4], 'should return the arguments provded'); + assert.deepEqual(echo(), [], 'should return no arguments'); + assert.deepEqual(echo(1), [1], 'should return the arguments provded'); + assert.deepEqual(echo(1,2), [1,2], 'should return the arguments provded'); + assert.deepEqual(echo(1,2,3), [1,2,3], 'should return the arguments provded'); + + assert.deepEqual(echo2(), [[], void 0], 'should return no arguments'); + assert.deepEqual(echo2(1), [[], 1], 'should return the arguments provded'); + assert.deepEqual(echo2(1,2), [[1], 2], 'should return the arguments provded'); + assert.deepEqual(echo2(1,2,3), [[1, 2], 3], 'should return the arguments provded'); + assert.deepEqual(echo2(1,2,3,4), [[1, 2, 3], 4], 'should return the arguments provded'); + + assert.deepEqual(echo3(), [[], void 0, void 0], 'should return no arguments'); + assert.deepEqual(echo3(1), [[], 1, void 0], 'should return the arguments provded'); + assert.deepEqual(echo3(1,2), [[], 1, 2], 'should return the arguments provded'); + assert.deepEqual(echo3(1,2,3), [[1], 2, 3], 'should return the arguments provded'); + assert.deepEqual(echo3(1,2,3,4), [[1, 2], 3, 4], 'should return the arguments provded'); }); - test("mapArgsWith", function () { + QUnit.test("mapArgsWith", function(assert) { var echo = _.unsplatl(function (args) { return args; }); function timesTwo (n) { return n * 2; } function plusOne (n) { return n + 1; } - deepEqual(_.mapArgsWith(timesTwo, echo)(), [], "should handle the empty case"); - deepEqual(_.mapArgsWith(timesTwo, echo)(42), [84], "should handle one arg"); - deepEqual(_.mapArgsWith(plusOne, echo)(1, 2, 3), [2, 3, 4], "should handle many args"); + assert.deepEqual(_.mapArgsWith(timesTwo, echo)(), [], "should handle the empty case"); + assert.deepEqual(_.mapArgsWith(timesTwo, echo)(42), [84], "should handle one arg"); + assert.deepEqual(_.mapArgsWith(plusOne, echo)(1, 2, 3), [2, 3, 4], "should handle many args"); - deepEqual(_.mapArgsWith(timesTwo)(echo)(), [], "should handle the empty case"); - deepEqual(_.mapArgsWith(timesTwo)(echo)(42), [84], "should handle one arg"); - deepEqual(_.mapArgsWith(plusOne)(echo)(1, 2, 3), [2, 3, 4], "should handle many args"); + assert.deepEqual(_.mapArgsWith(timesTwo)(echo)(), [], "should handle the empty case"); + assert.deepEqual(_.mapArgsWith(timesTwo)(echo)(42), [84], "should handle one arg"); + assert.deepEqual(_.mapArgsWith(plusOne)(echo)(1, 2, 3), [2, 3, 4], "should handle many args"); }); - test("flip2", function() { + QUnit.test("flip2", function(assert) { var div = function(n, d) { return n/d; }; - equal(_.flip2(div)(10,2), 0.2, 'should return a function that flips the first two args to a function'); + assert.equal(_.flip2(div)(10,2), 0.2, 'should return a function that flips the first two args to a function'); var obj = { num: 5, @@ -154,13 +154,13 @@ $(document).ready(function() { obj.reversedAddToNum = _.flip2(obj.addToNum); - deepEqual(obj.reversedAddToNum(1, 2), [7, 6], 'should function as a method combinator.'); + assert.deepEqual(obj.reversedAddToNum(1, 2), [7, 6], 'should function as a method combinator.'); }); - test("flip", function() { + QUnit.test("flip", function(assert) { var echo = function() { return Array.prototype.slice.call(arguments, 0); }; - deepEqual(_.flip(echo)(1, 2, 3, 4), [4, 3, 2, 1], 'should return a function that flips the first three or more args to a function'); + assert.deepEqual(_.flip(echo)(1, 2, 3, 4), [4, 3, 2, 1], 'should return a function that flips the first three or more args to a function'); var obj = { num: 5, @@ -169,17 +169,17 @@ $(document).ready(function() { obj.reversedAddToNum = _.flip(obj.addToNum); - deepEqual(obj.reversedAddToNum(1, 2), [7, 6], 'should function as a method combinator.'); + assert.deepEqual(obj.reversedAddToNum(1, 2), [7, 6], 'should function as a method combinator.'); }); - test("fnull", function() { + QUnit.test("fnull", function(assert) { var a = [1,2,3,null,5]; var b = [1,2,3,undefined,5]; var safeMult = _.fnull(function(total, n) { return total * n; }, 1, 1); - equal(_.reduce([1,2,3,5], safeMult), 30, 'should not fill in defaults when not needed'); - equal(_.reduce(a, safeMult), 30, 'should fill in defaults for null'); - equal(_.reduce(b, safeMult), 30, 'should fill in defaults for undefined'); + assert.equal(_.reduce([1,2,3,5], safeMult), 30, 'should not fill in defaults when not needed'); + assert.equal(_.reduce(a, safeMult), 30, 'should fill in defaults for null'); + assert.equal(_.reduce(b, safeMult), 30, 'should fill in defaults for undefined'); var obj = { a: 1, @@ -189,13 +189,13 @@ $(document).ready(function() { obj.getPropByNameOrDefault = _.fnull(obj.getPropByName, "fallback"); - equal(obj.getPropByNameOrDefault(), "fallback value", 'should function as a method combinator.'); + assert.equal(obj.getPropByNameOrDefault(), "fallback value", 'should function as a method combinator.'); }); - test("juxt", function() { + QUnit.test("juxt", function(assert) { var run = _.juxt(function(s, n) { return s.length + n; }, parseInt, _.always(108)); - deepEqual(run('42', 10), [12, 42, 108], 'should return a function that returns an array of the originally supplied functions called'); + assert.deepEqual(run('42', 10), [12, 42, 108], 'should return a function that returns an array of the originally supplied functions called'); var obj = { name: "Elizabeth 1", @@ -205,17 +205,17 @@ $(document).ready(function() { obj.firstAndLastChars = _.juxt(obj.firstChar, obj.lastChar); - deepEqual(obj.firstAndLastChars(), ['E', '1'], 'should function as a method combinator.'); + assert.deepEqual(obj.firstAndLastChars(), ['E', '1'], 'should function as a method combinator.'); }); - test("accessor", function() { + QUnit.test("accessor", function(assert) { var f = _.accessor('a'); - equal(f({a: 42}), 42, 'should retrieve a pluckable field'); - equal(f({z: 42}), undefined, 'should fail to retrieve a field if not there'); + assert.equal(f({a: 42}), 42, 'should retrieve a pluckable field'); + assert.equal(f({z: 42}), undefined, 'should fail to retrieve a field if not there'); }); - test("bound", function() { + QUnit.test("bound", function(assert) { var obj = { fun: function(b) { return this.a + b; @@ -228,13 +228,13 @@ $(document).ready(function() { var f = _.bound(obj, 'fun'); - equal(f('there'), 'hello there', 'should return concatenation of obj.a and string argument'); - throws(function() { + assert.equal(f('there'), 'hello there', 'should return concatenation of obj.a and string argument'); + assert.throws(function() { _.bound(obj, 'nofun'); }, TypeError, 'should throw for non-function properties'); }); - test("functionalize", function() { + QUnit.test("functionalize", function(assert) { var rect = { x: 2, y: 3, @@ -243,11 +243,11 @@ $(document).ready(function() { }; var areaFunc = _.functionalize(rect.area), extrudeFunc = _.functionalize(rect.extrude); - equal(areaFunc(rect), 6, "returned function's first arg becomes original method's `this`"); - equal(extrudeFunc(rect, 4).z, 4, "all arguments are passed along"); + assert.equal(areaFunc(rect), 6, "returned function's first arg becomes original method's `this`"); + assert.equal(extrudeFunc(rect, 4).z, 4, "all arguments are passed along"); }); - test("methodize", function() { + QUnit.test("methodize", function(assert) { function area(rect) {return rect.x * rect.y;} function extrude(rect, z) {return _.merge(rect, {z: z});} var rect = { @@ -256,7 +256,7 @@ $(document).ready(function() { area: _.methodize(area), extrude: _.methodize(extrude) }; - equal(rect.area(), 6, "returned method passes its receiver (`this`) as first arg to original function"); - equal(rect.extrude(4).z, 4, "all arguments are passed along"); + assert.equal(rect.area(), 6, "returned method passes its receiver (`this`) as first arg to original function"); + assert.equal(rect.extrude(4).z, 4, "all arguments are passed along"); }); }); diff --git a/test/function.dispatch.js b/test/function.dispatch.js index 366a377..4d11841 100644 --- a/test/function.dispatch.js +++ b/test/function.dispatch.js @@ -1,14 +1,14 @@ $(document).ready(function() { - module("underscore.function.dispatch"); + QUnit.module("underscore.function.dispatch"); - test('attempt', function() { + QUnit.test('attempt', function(assert) { var obj = {x: '', y: function() { return true; }, z: function() { return _.toArray(arguments).join(''); }}; - strictEqual(_.attempt(obj, 'x'), undefined); - strictEqual(_.attempt(obj, 'y'), true); - strictEqual(_.attempt(obj, 'z', 1, 2, 3), '123'); - strictEqual(_.attempt(null, 'x'), undefined); - strictEqual(_.attempt(undefined, 'x'), undefined); + assert.strictEqual(_.attempt(obj, 'x'), undefined); + assert.strictEqual(_.attempt(obj, 'y'), true); + assert.strictEqual(_.attempt(obj, 'z', 1, 2, 3), '123'); + assert.strictEqual(_.attempt(null, 'x'), undefined); + assert.strictEqual(_.attempt(undefined, 'x'), undefined); }); }); diff --git a/test/function.iterators.js b/test/function.iterators.js index 7d0c262..09f39dd 100644 --- a/test/function.iterators.js +++ b/test/function.iterators.js @@ -6,354 +6,354 @@ $(document).ready(function() { function naturalSmallerThan (x) { return _.iterators.List(_.range(0, x)); } - module("underscore.function.iterators"); + QUnit.module("underscore.function.iterators"); - test("List", function() { + QUnit.test("List", function(assert) { var i = _.iterators.List([1, 2, 3, 4, 5]); - equal(i(), 1, "should return the first element of the underlying array"); - equal(i(), 2, "should return the next element of the underlying array"); - equal(i(), 3, "should return the next element of the underlying array"); - equal(i(), 4, "should return the next element of the underlying array"); - equal(i(), 5, "should return the next element of the underlying array"); - equal(i(), void 0, "should return undefined when out of elements"); + assert.equal(i(), 1, "should return the first element of the underlying array"); + assert.equal(i(), 2, "should return the next element of the underlying array"); + assert.equal(i(), 3, "should return the next element of the underlying array"); + assert.equal(i(), 4, "should return the next element of the underlying array"); + assert.equal(i(), 5, "should return the next element of the underlying array"); + assert.equal(i(), void 0, "should return undefined when out of elements"); i = _.iterators.List([1, [2, 3, [4]], 5]); - equal(i(), 1, "should return the first element of the underlying array"); - notEqual(i(), 2, "should not do a deep traverse"); - equal(i(), 5, "should return the next element of the underlying array"); - equal(i(), void 0, "should return undefined when out of elements"); + assert.equal(i(), 1, "should return the first element of the underlying array"); + assert.notEqual(i(), 2, "should not do a deep traverse"); + assert.equal(i(), 5, "should return the next element of the underlying array"); + assert.equal(i(), void 0, "should return undefined when out of elements"); i = _.iterators.List([]); - equal(i(), void 0, "should return undefined when there are no elements"); + assert.equal(i(), void 0, "should return undefined when there are no elements"); i = _.iterators.List([[], [[]]]); - notEqual(i(), void 0, "should have a values given an empty tree"); + assert.notEqual(i(), void 0, "should have a values given an empty tree"); }); - test("Tree", function () { + QUnit.test("Tree", function(assert) { var i = _.iterators.Tree([]); - equal(i(), void 0, "should return undefined for an empty array"); + assert.equal(i(), void 0, "should return undefined for an empty array"); i = _.iterators.Tree([[], [[]]]); - equal(i(), void 0, "should return undefined for an empty tree"); + assert.equal(i(), void 0, "should return undefined for an empty tree"); i = _.iterators.Tree([1, 2, 3, 4, 5]); - equal(i(), 1, "should return the first element of the underlying array"); - equal(i(), 2, "should return the next element of the underlying array"); - equal(i(), 3, "should return the next element of the underlying array"); - equal(i(), 4, "should return the next element of the underlying array"); - equal(i(), 5, "should return the next element of the underlying array"); - equal(i(), void 0, "should return undefined when out of elements"); + assert.equal(i(), 1, "should return the first element of the underlying array"); + assert.equal(i(), 2, "should return the next element of the underlying array"); + assert.equal(i(), 3, "should return the next element of the underlying array"); + assert.equal(i(), 4, "should return the next element of the underlying array"); + assert.equal(i(), 5, "should return the next element of the underlying array"); + assert.equal(i(), void 0, "should return undefined when out of elements"); i = _.iterators.Tree([1, [2, 3, [4]], 5]); - equal(i(), 1, "should return the first element of the underlying array"); - equal(i(), 2, "should return the next element of the underlying array"); - equal(i(), 3, "should return the next element of the underlying array"); - equal(i(), 4, "should return the next element of the underlying array"); - equal(i(), 5, "should return the next element of the underlying array"); - equal(i(), void 0, "should return undefined when out of elements"); + assert.equal(i(), 1, "should return the first element of the underlying array"); + assert.equal(i(), 2, "should return the next element of the underlying array"); + assert.equal(i(), 3, "should return the next element of the underlying array"); + assert.equal(i(), 4, "should return the next element of the underlying array"); + assert.equal(i(), 5, "should return the next element of the underlying array"); + assert.equal(i(), void 0, "should return undefined when out of elements"); }); - test("Reduce", function () { + QUnit.test("Reduce", function(assert) { - equal( _.iterators.reduce(_.iterators.Tree([1, [2, 3, [4]], 5]), sum, 0), 15, "should fold an iterator with many elements"); + assert.equal( _.iterators.reduce(_.iterators.Tree([1, [2, 3, [4]], 5]), sum, 0), 15, "should fold an iterator with many elements"); - equal( _.iterators.reduce(_.iterators.Tree([[[4], []]]), sum, 42), 46, "should fold an iterator with one element"); + assert.equal( _.iterators.reduce(_.iterators.Tree([[[4], []]]), sum, 42), 46, "should fold an iterator with one element"); - equal( _.iterators.reduce(_.iterators.Tree([[], [[]]]), sum, 42), 42, "should fold an empty iterator"); + assert.equal( _.iterators.reduce(_.iterators.Tree([[], [[]]]), sum, 42), 42, "should fold an empty iterator"); - equal( _.iterators.reduce(_.iterators.Tree([1, [2, 3, [4]], 5]), sum), 15, "should fold an array with two or more elements"); + assert.equal( _.iterators.reduce(_.iterators.Tree([1, [2, 3, [4]], 5]), sum), 15, "should fold an array with two or more elements"); - equal( _.iterators.reduce(_.iterators.Tree([[[4], []]]), sum), 4, "should fold an array with one element"); + assert.equal( _.iterators.reduce(_.iterators.Tree([[[4], []]]), sum), 4, "should fold an array with one element"); - equal( _.iterators.reduce(_.iterators.Tree([[[], []]]), sum), void 0, "should fold an array with no elements"); + assert.equal( _.iterators.reduce(_.iterators.Tree([[[], []]]), sum), void 0, "should fold an array with no elements"); }); - test("Accumulate", function () { + QUnit.test("Accumulate", function(assert) { var i = _.iterators.accumulate(_.iterators.Tree([1, [2, 3, [4]], 5]), sum, 0); - equal(i(), 1, "should map an iterator with many elements"); - equal(i(), 3, "should map an iterator with many elements"); - equal(i(), 6, "should map an iterator with many elements"); - equal(i(), 10, "should map an iterator with many elements"); - equal(i(), 15, "should map an iterator with many elements"); - equal(i(), void 0); + assert.equal(i(), 1, "should map an iterator with many elements"); + assert.equal(i(), 3, "should map an iterator with many elements"); + assert.equal(i(), 6, "should map an iterator with many elements"); + assert.equal(i(), 10, "should map an iterator with many elements"); + assert.equal(i(), 15, "should map an iterator with many elements"); + assert.equal(i(), void 0); i = _.iterators.accumulate(_.iterators.Tree([[[4], []]]), sum, 42); - equal(i(), 46, "should map an iterator with one element"); - equal(i(), void 0); + assert.equal(i(), 46, "should map an iterator with one element"); + assert.equal(i(), void 0); i = _.iterators.accumulate(_.iterators.Tree([[[], []]]), sum, 42); - equal(i(), void 0, "should map an empty iterator"); + assert.equal(i(), void 0, "should map an empty iterator"); i = _.iterators.accumulate(_.iterators.Tree([1, [2, 3, [4]], 5]), sum); - equal(i(), 1, "should map an iterator with many elements"); - equal(i(), 3, "should map an iterator with many elements"); - equal(i(), 6, "should map an iterator with many elements"); - equal(i(), 10, "should map an iterator with many elements"); - equal(i(), 15, "should map an iterator with many elements"); - equal(i(), void 0); + assert.equal(i(), 1, "should map an iterator with many elements"); + assert.equal(i(), 3, "should map an iterator with many elements"); + assert.equal(i(), 6, "should map an iterator with many elements"); + assert.equal(i(), 10, "should map an iterator with many elements"); + assert.equal(i(), 15, "should map an iterator with many elements"); + assert.equal(i(), void 0); i = _.iterators.accumulate(_.iterators.Tree([[[4], []]]), sum); - equal(i(), 4, "should map an iterator with one element"); - equal(i(), void 0); + assert.equal(i(), 4, "should map an iterator with one element"); + assert.equal(i(), void 0); i = _.iterators.accumulate(_.iterators.Tree([[[], []]]), sum); - equal(i(), void 0); + assert.equal(i(), void 0); }); - test("Map", function () { + QUnit.test("Map", function(assert) { var i = _.iterators.map(_.iterators.Tree([1, [2, 3, [4]], 5]), square); - equal(i(), 1, "should map an iterator with many elements"); - equal(i(), 4, "should map an iterator with many elements"); - equal(i(), 9, "should map an iterator with many elements"); - equal(i(), 16, "should map an iterator with many elements"); - equal(i(), 25, "should map an iterator with many elements"); - equal(i(), void 0); + assert.equal(i(), 1, "should map an iterator with many elements"); + assert.equal(i(), 4, "should map an iterator with many elements"); + assert.equal(i(), 9, "should map an iterator with many elements"); + assert.equal(i(), 16, "should map an iterator with many elements"); + assert.equal(i(), 25, "should map an iterator with many elements"); + assert.equal(i(), void 0); i = _.iterators.map(_.iterators.Tree([[[4], []]]), square); - equal(i(), 16, "should map an iterator with one element"); - equal(i(), void 0); + assert.equal(i(), 16, "should map an iterator with one element"); + assert.equal(i(), void 0); i = _.iterators.map(_.iterators.Tree([[[], []]]), square); - equal(i(), void 0, "should map an empty iterator"); + assert.equal(i(), void 0, "should map an empty iterator"); }); - test("mapcat", function () { + QUnit.test("mapcat", function(assert) { var i = _.iterators.mapcat(_.iterators.Tree([1, [2]]), naturalSmallerThan); - equal(i(), 0, "should mapcat an iterator with many elements"); - equal(i(), 0, "should mapcat an iterator with many elements"); - equal(i(), 1, "should mapcat an iterator with many elements"); - equal(i(), void 0); + assert.equal(i(), 0, "should mapcat an iterator with many elements"); + assert.equal(i(), 0, "should mapcat an iterator with many elements"); + assert.equal(i(), 1, "should mapcat an iterator with many elements"); + assert.equal(i(), void 0); i = _.iterators.mapcat(_.iterators.Tree([[[1], []]]), naturalSmallerThan); - equal(i(), 0, "should mapcat an iterator with one element"); - equal(i(), void 0); + assert.equal(i(), 0, "should mapcat an iterator with one element"); + assert.equal(i(), void 0); i = _.iterators.mapcat(_.iterators.Tree([[[], []]]), naturalSmallerThan); - equal(i(), void 0, "should mapcat an empty iterator"); + assert.equal(i(), void 0, "should mapcat an empty iterator"); }); - test("filter", function() { + QUnit.test("filter", function(assert) { var i = _.iterators.filter(_.iterators.Tree([1, [2, 3, [4]], 5]), odd); - equal(i(),1); - equal(i(),3); - equal(i(),5); - equal(i(),void 0); + assert.equal(i(),1); + assert.equal(i(),3); + assert.equal(i(),5); + assert.equal(i(),void 0); i = _.iterators.filter(_.iterators.Tree([[[4], []]]), odd); - equal(i(),void 0); + assert.equal(i(),void 0); i = _.iterators.filter(_.iterators.Tree([[[], []]]), odd); - equal(i(),void 0); + assert.equal(i(),void 0); i = _.iterators.filter(_.iterators.List([2, 4, 6, 8, 10]), odd); - equal(i(),void 0); + assert.equal(i(),void 0); }); - test("slice", function() { - expect(0); - test("with two parameter", function() { - expect(0); - test("should return an identity iterator", function() { + QUnit.test("slice", function(assert) { + assert.expect(0); + QUnit.test("with two parameter", function(assert) { + assert.expect(0); + QUnit.test("should return an identity iterator", function(assert) { var i = _.iterators.slice(_.iterators.List([1, 2, 3, 4, 5]), 0); - equal(i(),1); - equal(i(),2); - equal(i(),3); - equal(i(),4); - equal(i(),5); - equal(i(),void 0); + assert.equal(i(),1); + assert.equal(i(),2); + assert.equal(i(),3); + assert.equal(i(),4); + assert.equal(i(),5); + assert.equal(i(),void 0); }); - test("should return a trailing iterator", function() { + QUnit.test("should return a trailing iterator", function(assert) { var i = _.iterators.slice(_.iterators.List([1, 2, 3, 4, 5]), 1); - equal(i(),2); - equal(i(),3); - equal(i(),4); - equal(i(),5); - equal(i(),void 0); + assert.equal(i(),2); + assert.equal(i(),3); + assert.equal(i(),4); + assert.equal(i(),5); + assert.equal(i(),void 0); }); - test("should return an empty iterator when out of range", function() { + QUnit.test("should return an empty iterator when out of range", function(assert) { var i = _.iterators.slice(_.iterators.List([1, 2, 3, 4, 5]), 5); - equal(i(),void 0); + assert.equal(i(),void 0); }); }); - test("with three parameters", function() { - expect(0); - test("should return an identity iterator", function() { + QUnit.test("with three parameters", function(assert) { + assert.expect(0); + QUnit.test("should return an identity iterator", function(assert) { var i = _.iterators.slice(_.iterators.List([1, 2, 3, 4, 5]), 0, 5); - equal(i(),1); - equal(i(),2); - equal(i(),3); - equal(i(),4); - equal(i(),5); - equal(i(),void 0); + assert.equal(i(),1); + assert.equal(i(),2); + assert.equal(i(),3); + assert.equal(i(),4); + assert.equal(i(),5); + assert.equal(i(),void 0); i = _.iterators.slice(_.iterators.List([1, 2, 3, 4, 5]), 0, 99); - equal(i(),1); - equal(i(),2); - equal(i(),3); - equal(i(),4); - equal(i(),5); - equal(i(),void 0); + assert.equal(i(),1); + assert.equal(i(),2); + assert.equal(i(),3); + assert.equal(i(),4); + assert.equal(i(),5); + assert.equal(i(),void 0); }); - test("should return a leading iterator", function() { + QUnit.test("should return a leading iterator", function(assert) { var i = _.iterators.slice(_.iterators.List([1, 2, 3, 4, 5]), 0, 4); - equal(i(),1); - equal(i(),2); - equal(i(),3); - equal(i(),4); - equal(i(),void 0); + assert.equal(i(),1); + assert.equal(i(),2); + assert.equal(i(),3); + assert.equal(i(),4); + assert.equal(i(),void 0); }); - test("should return a trailing iterator", function() { + QUnit.test("should return a trailing iterator", function(assert) { var i = _.iterators.slice(_.iterators.List([1, 2, 3, 4, 5]), 1, 4); - equal(i(),2); - equal(i(),3); - equal(i(),4); - equal(i(),5); - equal(i(),void 0); + assert.equal(i(),2); + assert.equal(i(),3); + assert.equal(i(),4); + assert.equal(i(),5); + assert.equal(i(),void 0); i = _.iterators.slice(_.iterators.List([1, 2, 3, 4, 5]), 1, 99); - equal(i(),2); - equal(i(),3); - equal(i(),4); - equal(i(),5); - equal(i(),void 0); + assert.equal(i(),2); + assert.equal(i(),3); + assert.equal(i(),4); + assert.equal(i(),5); + assert.equal(i(),void 0); }); - test("should return an inner iterator", function() { + QUnit.test("should return an inner iterator", function(assert) { var i = _.iterators.slice(_.iterators.List([1, 2, 3, 4, 5]), 1, 3); - equal(i(),2); - equal(i(),3); - equal(i(),4); - equal(i(),void 0); + assert.equal(i(),2); + assert.equal(i(),3); + assert.equal(i(),4); + assert.equal(i(),void 0); }); - test("should return an empty iterator when given a zero length", function() { + QUnit.test("should return an empty iterator when given a zero length", function(assert) { var i = _.iterators.slice(_.iterators.List([1, 2, 3, 4, 5]), 1, 0); - equal(i(),void 0); + assert.equal(i(),void 0); }); - test("should return an empty iterator when out of range", function() { + QUnit.test("should return an empty iterator when out of range", function(assert) { var i = _.iterators.slice(_.iterators.List([1, 2, 3, 4, 5]), 5, 1); - equal(i(),void 0); + assert.equal(i(),void 0); }); }); }); - test("drop", function() { - expect(0); - test("should drop the number of items dropped", function() { + QUnit.test("drop", function(assert) { + assert.expect(0); + QUnit.test("should drop the number of items dropped", function(assert) { var i = _.iterators.drop(_.iterators.List([1, 2, 3, 4, 5]), 2); - equal(i(),3); - equal(i(),4); - equal(i(),5); - equal(i(),void 0); + assert.equal(i(),3); + assert.equal(i(),4); + assert.equal(i(),5); + assert.equal(i(),void 0); }); - test("should handle overdropping", function() { + QUnit.test("should handle overdropping", function(assert) { var i = _.iterators.drop(_.iterators.List([1, 2, 3, 4, 5]), 99); - equal(i(),void 0); + assert.equal(i(),void 0); }); - test("should handle underdropping", function() { + QUnit.test("should handle underdropping", function(assert) { var i = _.iterators.drop(_.iterators.List([1, 2, 3, 4, 5]), 0); - equal(i(),1); - equal(i(),2); - equal(i(),3); - equal(i(),4); - equal(i(),5); - equal(i(),void 0); + assert.equal(i(),1); + assert.equal(i(),2); + assert.equal(i(),3); + assert.equal(i(),4); + assert.equal(i(),5); + assert.equal(i(),void 0); }); - test("should default to one", function() { + QUnit.test("should default to one", function(assert) { var i = _.iterators.drop(_.iterators.List([1, 2, 3, 4, 5])); - equal(i(),2); - equal(i(),3); - equal(i(),4); - equal(i(),5); - equal(i(),void 0); + assert.equal(i(),2); + assert.equal(i(),3); + assert.equal(i(),4); + assert.equal(i(),5); + assert.equal(i(),void 0); }); }); - test("accumulateWithReturn", function() { - expect(0); - test("should pass the state and result in a pair", function() { + QUnit.test("accumulateWithReturn", function(assert) { + assert.expect(0); + QUnit.test("should pass the state and result in a pair", function(assert) { var i = _.iterators.accumulateWithReturn(_.iterators.List([1, 2, 3, 4, 5]), function(state, element) { return [state + element, 'Total is ' + (state + element)]; }, 0); - equal(i(),'Total is 1'); - equal(i(),'Total is 3'); - equal(i(),'Total is 6'); - equal(i(),'Total is 10'); - equal(i(),'Total is 15'); + assert.equal(i(),'Total is 1'); + assert.equal(i(),'Total is 3'); + assert.equal(i(),'Total is 6'); + assert.equal(i(),'Total is 10'); + assert.equal(i(),'Total is 15'); }); }); - test("unfold", function() { - expect(0); - test("should unfold and include the seed", function() { + QUnit.test("unfold", function(assert) { + assert.expect(0); + QUnit.test("should unfold and include the seed", function(assert) { var i = _.iterators.unfold(0, function(n) { return n + 1; }); - equal(i(),0); - equal(i(),1); - equal(i(),2); + assert.equal(i(),0); + assert.equal(i(),1); + assert.equal(i(),2); }); - test("should not unfold without a seed", function() { + QUnit.test("should not unfold without a seed", function(assert) { var i = _.iterators.unfold(void 0, function(n) { return n + 1; }); - equal(i(),void 0); - equal(i(),void 0); - equal(i(),void 0); - equal(i(),void 0); + assert.equal(i(),void 0); + assert.equal(i(),void 0); + assert.equal(i(),void 0); + assert.equal(i(),void 0); }); }); - test("unfoldWithReturn", function() { - expect(0); - test("should unfold and throw off a value", function() { + QUnit.test("unfoldWithReturn", function(assert) { + assert.expect(0); + QUnit.test("should unfold and throw off a value", function(assert) { var i = _.iterators.unfoldWithReturn(1, function(n) { return [n + 1, n * n]; }); - equal(i(),1); - equal(i(),4); - equal(i(),9); - equal(i(),16); + assert.equal(i(),1); + assert.equal(i(),4); + assert.equal(i(),9); + assert.equal(i(),16); }); - test("should halt if it returns undefined", function() { + QUnit.test("should halt if it returns undefined", function(assert) { var i = _.iterators.unfoldWithReturn(1, function(n) { return [n + 1, n === 1 ? void 0 : n * n]; }); - equal(i(),void 0); - equal(i(),void 0); - equal(i(),void 0); - equal(i(),void 0); + assert.equal(i(),void 0); + assert.equal(i(),void 0); + assert.equal(i(),void 0); + assert.equal(i(),void 0); }); - test("should halt if the state becomes undefined", function() { + QUnit.test("should halt if the state becomes undefined", function(assert) { var i = _.iterators.unfoldWithReturn(1, function(n) { return [(n === 3 ? void 0 : n + 1), (n === void 0 ? 100 : n * n)]; }); - equal(i(),1); - equal(i(),4); - equal(i(),9); - equal(i(),void 0); + assert.equal(i(),1); + assert.equal(i(),4); + assert.equal(i(),9); + assert.equal(i(),void 0); }); }); - test("cycle", function() { - expect(0); - test("empty array always returns undefined", function(){ + QUnit.test("cycle", function(assert) { + assert.expect(0); + QUnit.test("empty array always returns undefined", function(assert){ var iter = _.iterators.cycle([]); - equal(iter(), void 0); - equal(iter(), void 0); - equal(iter(), void 0); + assert.equal(iter(), void 0); + assert.equal(iter(), void 0); + assert.equal(iter(), void 0); }); - test("one item array always returns the item", function() { + QUnit.test("one item array always returns the item", function(assert) { var iter = _.iterators.cycle(['a']); - equal(iter(), 'a'); - equal(iter(), 'a'); - equal(iter(), 'a'); + assert.equal(iter(), 'a'); + assert.equal(iter(), 'a'); + assert.equal(iter(), 'a'); }); - test("multiple item array endlessly loops over the array", function(){ + QUnit.test("multiple item array endlessly loops over the array", function(assert){ var letters = ['a', 'b', 'c', 'd', 'e']; var iter = _.iterators.cycle(letters); for(var n = 0; n < 5; n++){ for(var j = 0; j < letters.length; j++){ - equal(iter(), letters[j]); + assert.equal(iter(), letters[j]); } } }); diff --git a/test/function.predicates.js b/test/function.predicates.js index 770bde1..791d2e7 100644 --- a/test/function.predicates.js +++ b/test/function.predicates.js @@ -1,175 +1,175 @@ $(document).ready(function() { - module("underscore.function.predicates"); + QUnit.module("underscore.function.predicates"); - test("isInstanceOf", function() { - equal(_.isInstanceOf([], Array), true, 'should identify arrays'); - equal(_.isInstanceOf(null, Array), false, 'should identify that null is not an array instance'); + QUnit.test("isInstanceOf", function(assert) { + assert.equal(_.isInstanceOf([], Array), true, 'should identify arrays'); + assert.equal(_.isInstanceOf(null, Array), false, 'should identify that null is not an array instance'); }); - test("isAssociative", function() { - equal(_.isAssociative({}), true, 'should identify that a map is associative'); - equal(_.isAssociative(function(){}), true, 'should identify that a function is associative'); - equal(_.isAssociative([]), true, 'should identify that an array is associative'); - equal(_.isAssociative(new Array(10)), true, 'should identify that an array is associative'); - - equal(_.isAssociative(1), false, 'should identify non-associative things'); - equal(_.isAssociative(0), false, 'should identify non-associative things'); - equal(_.isAssociative(-1), false, 'should identify non-associative things'); - equal(_.isAssociative(3.14), false, 'should identify non-associative things'); - equal(_.isAssociative('undefined'), false, 'should identify non-associative things'); - equal(_.isAssociative(''), false, 'should identify non-associative things'); - equal(_.isAssociative(NaN), false, 'should identify non-associative things'); - equal(_.isAssociative(Infinity), false, 'should identify non-associative things'); - equal(_.isAssociative(true), false, 'should identify non-associative things'); + QUnit.test("isAssociative", function(assert) { + assert.equal(_.isAssociative({}), true, 'should identify that a map is associative'); + assert.equal(_.isAssociative(function(){}), true, 'should identify that a function is associative'); + assert.equal(_.isAssociative([]), true, 'should identify that an array is associative'); + assert.equal(_.isAssociative(new Array(10)), true, 'should identify that an array is associative'); + + assert.equal(_.isAssociative(1), false, 'should identify non-associative things'); + assert.equal(_.isAssociative(0), false, 'should identify non-associative things'); + assert.equal(_.isAssociative(-1), false, 'should identify non-associative things'); + assert.equal(_.isAssociative(3.14), false, 'should identify non-associative things'); + assert.equal(_.isAssociative('undefined'), false, 'should identify non-associative things'); + assert.equal(_.isAssociative(''), false, 'should identify non-associative things'); + assert.equal(_.isAssociative(NaN), false, 'should identify non-associative things'); + assert.equal(_.isAssociative(Infinity), false, 'should identify non-associative things'); + assert.equal(_.isAssociative(true), false, 'should identify non-associative things'); }); - test("isIndexed", function() { - equal(_.isIndexed([]), true, 'should identify indexed objects'); - equal(_.isIndexed([1,2,3]), true, 'should identify indexed objects'); - equal(_.isIndexed(new Array(10)), true, 'should identify indexed objects'); - equal(_.isIndexed(""), true, 'should identify indexed objects'); - equal(_.isIndexed("abc"), true, 'should identify indexed objects'); - - equal(_.isIndexed(1), false, 'should identify when something is not an indexed object'); - equal(_.isIndexed(0), false, 'should identify when something is not an indexed object'); - equal(_.isIndexed(-1), false, 'should identify when something is not an indexed object'); - equal(_.isIndexed(3.14), false, 'should identify when something is not an indexed object'); - equal(_.isIndexed(undefined), false, 'should identify when something is not an indexed object'); - equal(_.isIndexed(NaN), false, 'should identify when something is not an indexed object'); - equal(_.isIndexed(Infinity), false, 'should identify when something is not an indexed object'); - equal(_.isIndexed(true), false, 'should identify when something is not an indexed object'); - equal(_.isIndexed(false), false, 'should identify when something is not an indexed object'); - equal(_.isIndexed(function(){}), false, 'should identify when something is not an indexed object'); + QUnit.test("isIndexed", function(assert) { + assert.equal(_.isIndexed([]), true, 'should identify indexed objects'); + assert.equal(_.isIndexed([1,2,3]), true, 'should identify indexed objects'); + assert.equal(_.isIndexed(new Array(10)), true, 'should identify indexed objects'); + assert.equal(_.isIndexed(""), true, 'should identify indexed objects'); + assert.equal(_.isIndexed("abc"), true, 'should identify indexed objects'); + + assert.equal(_.isIndexed(1), false, 'should identify when something is not an indexed object'); + assert.equal(_.isIndexed(0), false, 'should identify when something is not an indexed object'); + assert.equal(_.isIndexed(-1), false, 'should identify when something is not an indexed object'); + assert.equal(_.isIndexed(3.14), false, 'should identify when something is not an indexed object'); + assert.equal(_.isIndexed(undefined), false, 'should identify when something is not an indexed object'); + assert.equal(_.isIndexed(NaN), false, 'should identify when something is not an indexed object'); + assert.equal(_.isIndexed(Infinity), false, 'should identify when something is not an indexed object'); + assert.equal(_.isIndexed(true), false, 'should identify when something is not an indexed object'); + assert.equal(_.isIndexed(false), false, 'should identify when something is not an indexed object'); + assert.equal(_.isIndexed(function(){}), false, 'should identify when something is not an indexed object'); }); - test("isSequential", function() { - equal(_.isSequential(new Array(10)), true, 'should identify sequential objects'); - equal(_.isSequential([1,2]), true, 'should identify sequential objects'); - equal(_.isSequential(arguments), true, 'should identify sequential objects'); - - equal(_.isSequential({}), false, 'should identify when something is not sequential'); - equal(_.isSequential(function(){}), false, 'should identify when something is not sequential'); - equal(_.isSequential(1), false, 'should identify when something is not sequential'); - equal(_.isSequential(0), false, 'should identify when something is not sequential'); - equal(_.isSequential(-1), false, 'should identify when something is not sequential'); - equal(_.isSequential(3.14), false, 'should identify when something is not sequential'); - equal(_.isSequential('undefined'), false, 'should identify when something is not sequential'); - equal(_.isSequential(''), false, 'should identify when something is not sequential'); - equal(_.isSequential(NaN), false, 'should identify when something is not sequential'); - equal(_.isSequential(Infinity), false, 'should identify when something is not sequential'); - equal(_.isSequential(true), false, 'should identify when something is not sequential'); + QUnit.test("isSequential", function(assert) { + assert.equal(_.isSequential(new Array(10)), true, 'should identify sequential objects'); + assert.equal(_.isSequential([1,2]), true, 'should identify sequential objects'); + assert.equal(_.isSequential(arguments), true, 'should identify sequential objects'); + + assert.equal(_.isSequential({}), false, 'should identify when something is not sequential'); + assert.equal(_.isSequential(function(){}), false, 'should identify when something is not sequential'); + assert.equal(_.isSequential(1), false, 'should identify when something is not sequential'); + assert.equal(_.isSequential(0), false, 'should identify when something is not sequential'); + assert.equal(_.isSequential(-1), false, 'should identify when something is not sequential'); + assert.equal(_.isSequential(3.14), false, 'should identify when something is not sequential'); + assert.equal(_.isSequential('undefined'), false, 'should identify when something is not sequential'); + assert.equal(_.isSequential(''), false, 'should identify when something is not sequential'); + assert.equal(_.isSequential(NaN), false, 'should identify when something is not sequential'); + assert.equal(_.isSequential(Infinity), false, 'should identify when something is not sequential'); + assert.equal(_.isSequential(true), false, 'should identify when something is not sequential'); }); - test("isPlainObject", function() { + QUnit.test("isPlainObject", function(assert) { function SomeConstructor() {} - equal(_.isPlainObject({}), true, 'should identify empty objects'); - equal(_.isPlainObject({a: 1, b: 2}), true, 'should identify objects'); - equal(_.isPlainObject(Object.create(null)), false, 'should reject objects with no prototype'); - equal(_.isPlainObject(new SomeConstructor), false, 'should reject instances constructed by something other than Object'); - - equal(_.isPlainObject([]), false, 'should identify when something is not a plain object'); - equal(_.isPlainObject(function(){}), false, 'should identify when something is not a plain object'); - equal(_.isPlainObject(null), false, 'should identify when something is not a plain object'); - equal(_.isPlainObject(1), false, 'should identify when something is not a plain object'); - equal(_.isPlainObject(0), false, 'should identify when something is not a plain object'); - equal(_.isPlainObject(-1), false, 'should identify when something is not a plain object'); - equal(_.isPlainObject(3.14), false, 'should identify when something is not a plain object'); - equal(_.isPlainObject('undefined'), false, 'should identify when something is not a plain object'); - equal(_.isPlainObject(''), false, 'should identify when something is not a plain object'); - equal(_.isPlainObject(NaN), false, 'should identify when something is not a plain object'); - equal(_.isPlainObject(Infinity), false, 'should identify when something is not a plain object'); - equal(_.isPlainObject(true), false, 'should identify when something is not a plain object'); + assert.equal(_.isPlainObject({}), true, 'should identify empty objects'); + assert.equal(_.isPlainObject({a: 1, b: 2}), true, 'should identify objects'); + assert.equal(_.isPlainObject(Object.create(null)), false, 'should reject objects with no prototype'); + assert.equal(_.isPlainObject(new SomeConstructor), false, 'should reject instances constructed by something other than Object'); + + assert.equal(_.isPlainObject([]), false, 'should identify when something is not a plain object'); + assert.equal(_.isPlainObject(function(){}), false, 'should identify when something is not a plain object'); + assert.equal(_.isPlainObject(null), false, 'should identify when something is not a plain object'); + assert.equal(_.isPlainObject(1), false, 'should identify when something is not a plain object'); + assert.equal(_.isPlainObject(0), false, 'should identify when something is not a plain object'); + assert.equal(_.isPlainObject(-1), false, 'should identify when something is not a plain object'); + assert.equal(_.isPlainObject(3.14), false, 'should identify when something is not a plain object'); + assert.equal(_.isPlainObject('undefined'), false, 'should identify when something is not a plain object'); + assert.equal(_.isPlainObject(''), false, 'should identify when something is not a plain object'); + assert.equal(_.isPlainObject(NaN), false, 'should identify when something is not a plain object'); + assert.equal(_.isPlainObject(Infinity), false, 'should identify when something is not a plain object'); + assert.equal(_.isPlainObject(true), false, 'should identify when something is not a plain object'); }); - test("isEven", function() { - equal(_.isEven(0), true, 'should identify even numbers'); - equal(_.isEven(2), true, 'should identify even numbers'); - equal(_.isEven(-2), true, 'should identify even numbers'); - equal(_.isEven(1), false, 'should identify non-even numbers'); - equal(_.isEven(null), false, 'should return false for non-numbers'); - equal(_.isEven(undefined), false, 'should return false for non-numbers'); - equal(_.isEven([]), false, 'should return false for non-numbers'); - equal(_.isEven(NaN), false, 'should return false for non-numbers'); + QUnit.test("isEven", function(assert) { + assert.equal(_.isEven(0), true, 'should identify even numbers'); + assert.equal(_.isEven(2), true, 'should identify even numbers'); + assert.equal(_.isEven(-2), true, 'should identify even numbers'); + assert.equal(_.isEven(1), false, 'should identify non-even numbers'); + assert.equal(_.isEven(null), false, 'should return false for non-numbers'); + assert.equal(_.isEven(undefined), false, 'should return false for non-numbers'); + assert.equal(_.isEven([]), false, 'should return false for non-numbers'); + assert.equal(_.isEven(NaN), false, 'should return false for non-numbers'); }); - test("isOdd", function() { - equal(_.isOdd(1), true, 'should identify odd numbers'); - equal(_.isOdd(33), true, 'should identify odd numbers'); - equal(_.isOdd(-55), true, 'should identify odd numbers'); - equal(_.isOdd(10), false, 'should identify non-odd numbers'); - equal(_.isOdd(null), false, 'should return false for non-numbers'); - equal(_.isOdd(undefined), false, 'should return false for non-numbers'); - equal(_.isOdd([]), false, 'should return false for non-numbers'); - equal(_.isOdd(NaN), false, 'should return false for non-numbers'); + QUnit.test("isOdd", function(assert) { + assert.equal(_.isOdd(1), true, 'should identify odd numbers'); + assert.equal(_.isOdd(33), true, 'should identify odd numbers'); + assert.equal(_.isOdd(-55), true, 'should identify odd numbers'); + assert.equal(_.isOdd(10), false, 'should identify non-odd numbers'); + assert.equal(_.isOdd(null), false, 'should return false for non-numbers'); + assert.equal(_.isOdd(undefined), false, 'should return false for non-numbers'); + assert.equal(_.isOdd([]), false, 'should return false for non-numbers'); + assert.equal(_.isOdd(NaN), false, 'should return false for non-numbers'); }); - test("isPositive", function() { - equal(_.isPositive(1), true, 'should identify positive numbers'); - equal(_.isPositive(-1), false, 'should identify non-positive numbers'); - equal(_.isPositive(0), false, 'should identify non-positive numbers'); - equal(_.isPositive(+0), false, 'should identify non-positive numbers'); + QUnit.test("isPositive", function(assert) { + assert.equal(_.isPositive(1), true, 'should identify positive numbers'); + assert.equal(_.isPositive(-1), false, 'should identify non-positive numbers'); + assert.equal(_.isPositive(0), false, 'should identify non-positive numbers'); + assert.equal(_.isPositive(+0), false, 'should identify non-positive numbers'); }); - test("isNegative", function() { - equal(_.isNegative(-1), true, 'should identify negative numbers'); - equal(_.isNegative(0), false, 'should identify non-negative numbers'); - equal(_.isNegative(110), false, 'should identify non-negative numbers'); - equal(_.isNegative(-0), false, 'should identify non-negative numbers'); + QUnit.test("isNegative", function(assert) { + assert.equal(_.isNegative(-1), true, 'should identify negative numbers'); + assert.equal(_.isNegative(0), false, 'should identify non-negative numbers'); + assert.equal(_.isNegative(110), false, 'should identify non-negative numbers'); + assert.equal(_.isNegative(-0), false, 'should identify non-negative numbers'); }); - test("isZero", function() { - equal(_.isZero(0), true, 'should know zero'); - equal(_.isZero(-0), true, 'should know zero'); - equal(_.isZero(+0), true, 'should know zero'); - equal(_.isZero(1), false, 'should know non-zero'); - equal(_.isZero(-1), false, 'should know non-zero'); + QUnit.test("isZero", function(assert) { + assert.equal(_.isZero(0), true, 'should know zero'); + assert.equal(_.isZero(-0), true, 'should know zero'); + assert.equal(_.isZero(+0), true, 'should know zero'); + assert.equal(_.isZero(1), false, 'should know non-zero'); + assert.equal(_.isZero(-1), false, 'should know non-zero'); }); - test("isNumeric", function() { + QUnit.test("isNumeric", function(assert) { // Integer Literals - equal(_.isNumeric("-10"), true, "should identify Negative integer string"); - equal(_.isNumeric("0"), true, "should identify Zero string"); - equal(_.isNumeric("5"), true, "should identify Positive integer string"); - equal(_.isNumeric(-16), true, "should identify Negative integer number"); - equal(_.isNumeric(0), true, "should identify Zero integer number"); - equal(_.isNumeric(32), true, "should identify Positive integer number"); - equal(_.isNumeric("040"), true, "should identify Octal integer literal string"); - equal(_.isNumeric(0144), true, "should identify Octal integer literal"); - equal(_.isNumeric("0xFF"), true, "should identify Hexadecimal integer literal string"); - equal(_.isNumeric(0xFFF), true, "should identify Hexadecimal integer literal"); + assert.equal(_.isNumeric("-10"), true, "should identify Negative integer string"); + assert.equal(_.isNumeric("0"), true, "should identify Zero string"); + assert.equal(_.isNumeric("5"), true, "should identify Positive integer string"); + assert.equal(_.isNumeric(-16), true, "should identify Negative integer number"); + assert.equal(_.isNumeric(0), true, "should identify Zero integer number"); + assert.equal(_.isNumeric(32), true, "should identify Positive integer number"); + assert.equal(_.isNumeric("040"), true, "should identify Octal integer literal string"); + assert.equal(_.isNumeric(0144), true, "should identify Octal integer literal"); + assert.equal(_.isNumeric("0xFF"), true, "should identify Hexadecimal integer literal string"); + assert.equal(_.isNumeric(0xFFF), true, "should identify Hexadecimal integer literal"); // Foating-Point Literals - equal(_.isNumeric("-1.6"), true, "should identify Negative floating point string"); - equal(_.isNumeric("4.536"), true, "should identify Positive floating point string"); - equal(_.isNumeric(-2.6), true, "should identify Negative floating point number"); - equal(_.isNumeric(3.1415), true, "should identify Positive floating point number"); - equal(_.isNumeric(8e5), true, "should identify Exponential notation"); - equal(_.isNumeric("123e-2"), true, "should identify Exponential notation string"); + assert.equal(_.isNumeric("-1.6"), true, "should identify Negative floating point string"); + assert.equal(_.isNumeric("4.536"), true, "should identify Positive floating point string"); + assert.equal(_.isNumeric(-2.6), true, "should identify Negative floating point number"); + assert.equal(_.isNumeric(3.1415), true, "should identify Positive floating point number"); + assert.equal(_.isNumeric(8e5), true, "should identify Exponential notation"); + assert.equal(_.isNumeric("123e-2"), true, "should identify Exponential notation string"); // Non-Numeric values - equal(_.isNumeric(""), false, "should identify Empty string"); - equal(_.isNumeric(" "), false, "should identify Whitespace characters string"); - equal(_.isNumeric("\t\t"), false, "should identify Tab characters string"); - equal(_.isNumeric("abcdefghijklm1234567890"), false, "should identify Alphanumeric character string"); - equal(_.isNumeric("xabcdefx"), false, "should identify Non-numeric character string"); - equal(_.isNumeric(true), false, "should identify Boolean true literal"); - equal(_.isNumeric(false), false, "should identify Boolean false literal"); - equal(_.isNumeric("bcfed5.2"), false, "should identify Number with preceding non-numeric characters"); - equal(_.isNumeric("7.2acdgs"), false, "should identify Number with trailling non-numeric characters"); - equal(_.isNumeric(undefined), false, "should identify Undefined value"); - equal(_.isNumeric(null), false, "should identify Null value"); - equal(_.isNumeric(NaN), false, "should identify NaN value"); - equal(_.isNumeric(Infinity), false, "should identify Infinity primitive"); - equal(_.isNumeric(Number.POSITIVE_INFINITY), false, "should identify Positive Infinity"); - equal(_.isNumeric(Number.NEGATIVE_INFINITY), false, "should identify Negative Infinity"); - equal(_.isNumeric(new Date(2009,1,1)), false, "should identify Date object"); - equal(_.isNumeric({}), false, "should identify Empty object"); - equal(_.isNumeric(function(){}), false, "should identify Instance of a function"); + assert.equal(_.isNumeric(""), false, "should identify Empty string"); + assert.equal(_.isNumeric(" "), false, "should identify Whitespace characters string"); + assert.equal(_.isNumeric("\t\t"), false, "should identify Tab characters string"); + assert.equal(_.isNumeric("abcdefghijklm1234567890"), false, "should identify Alphanumeric character string"); + assert.equal(_.isNumeric("xabcdefx"), false, "should identify Non-numeric character string"); + assert.equal(_.isNumeric(true), false, "should identify Boolean true literal"); + assert.equal(_.isNumeric(false), false, "should identify Boolean false literal"); + assert.equal(_.isNumeric("bcfed5.2"), false, "should identify Number with preceding non-numeric characters"); + assert.equal(_.isNumeric("7.2acdgs"), false, "should identify Number with trailling non-numeric characters"); + assert.equal(_.isNumeric(undefined), false, "should identify Undefined value"); + assert.equal(_.isNumeric(null), false, "should identify Null value"); + assert.equal(_.isNumeric(NaN), false, "should identify NaN value"); + assert.equal(_.isNumeric(Infinity), false, "should identify Infinity primitive"); + assert.equal(_.isNumeric(Number.POSITIVE_INFINITY), false, "should identify Positive Infinity"); + assert.equal(_.isNumeric(Number.NEGATIVE_INFINITY), false, "should identify Negative Infinity"); + assert.equal(_.isNumeric(new Date(2009,1,1)), false, "should identify Date object"); + assert.equal(_.isNumeric({}), false, "should identify Empty object"); + assert.equal(_.isNumeric(function(){}), false, "should identify Instance of a function"); }); - test("isInteger and isFloat", function() { + QUnit.test("isInteger and isFloat", function(assert) { var integerChecks = [ {value: "-10", message: "should identify Negative integer string"}, {value: "0", message: "should identify Zero string"}, @@ -204,7 +204,7 @@ $(document).ready(function() { var testMultiple = function(cases, fn, result){ for (var i = 0; i < cases.length; i++) { - equal(fn(cases[i].value), result, cases[i].message); + assert.equal(fn(cases[i].value), result, cases[i].message); } }; @@ -217,31 +217,31 @@ $(document).ready(function() { testMultiple(negativeChecks, _.isFloat, false); }); - test("isIncreasing", function() { + QUnit.test("isIncreasing", function(assert) { var inc = [1,2,3]; var incNM = [1,2,3,3,4]; var dec = [5,4,3,2,1]; - equal(_.isIncreasing.apply(null, inc), true, 'should identify when its arguments monotonically increase'); - equal(_.isIncreasing.apply(null, incNM), false, 'should identify when its arguments monotonically increase'); - equal(_.isIncreasing.apply(null, dec), false, 'should identify when its arguments do not increase'); + assert.equal(_.isIncreasing.apply(null, inc), true, 'should identify when its arguments monotonically increase'); + assert.equal(_.isIncreasing.apply(null, incNM), false, 'should identify when its arguments monotonically increase'); + assert.equal(_.isIncreasing.apply(null, dec), false, 'should identify when its arguments do not increase'); }); - test("isDecreasing", function() { + QUnit.test("isDecreasing", function(assert) { var inc = [1,2,3]; var incNM = [1,2,3,3,4]; var dec = [5,4,3,2,1]; var decNM = [5,4,3,3,2,1]; - equal(_.isDecreasing.apply(null, inc), false, 'should identify when its arguments monotonically decrease'); - equal(_.isDecreasing.apply(null, incNM), false, 'should identify when its arguments monotonically decrease'); - equal(_.isDecreasing.apply(null, dec), true, 'should identify when its arguments do not decrease'); - equal(_.isDecreasing.apply(null, decNM), false, 'should identify when its arguments monotonically decrease'); + assert.equal(_.isDecreasing.apply(null, inc), false, 'should identify when its arguments monotonically decrease'); + assert.equal(_.isDecreasing.apply(null, incNM), false, 'should identify when its arguments monotonically decrease'); + assert.equal(_.isDecreasing.apply(null, dec), true, 'should identify when its arguments do not decrease'); + assert.equal(_.isDecreasing.apply(null, decNM), false, 'should identify when its arguments monotonically decrease'); }); - test("isValidDate", function() { - equal(_.isValidDate(new Date), true, 'should recognize a fresh Date instance as valid'); - equal(!_.isValidDate(new Date("bad date")), true, 'should recognize a Date constructed with gibberish'); + QUnit.test("isValidDate", function(assert) { + assert.equal(_.isValidDate(new Date), true, 'should recognize a fresh Date instance as valid'); + assert.equal(!_.isValidDate(new Date("bad date")), true, 'should recognize a Date constructed with gibberish'); }); }); diff --git a/test/index.html b/test/index.html index 7cfe9b5..818da37 100644 --- a/test/index.html +++ b/test/index.html @@ -1,13 +1,13 @@ - + Underscore-contrib Test Suite - - - - - + + + + + diff --git a/test/object.builders.js b/test/object.builders.js index 02f7dec..0436d83 100644 --- a/test/object.builders.js +++ b/test/object.builders.js @@ -1,31 +1,31 @@ $(document).ready(function() { - module("underscore.object.builders"); + QUnit.module("underscore.object.builders"); - test("merge", function() { + QUnit.test("merge", function(assert) { var o = {'a': 1, 'b': 2}; - deepEqual(_.merge(o), {a: 1, b: 2}, 'should return a copy of the object if given only one'); - deepEqual(_.merge({'a': 1, 'b': 2}, {b: 42}), {'a': 1, b: 42}, 'should merge two objects'); - deepEqual(_.merge({a: 1, b: 2}, {b: 42}, {c: 3}), {a: 1, b: 42, c: 3}, 'should merge three or more objects'); - deepEqual(_.merge({a: 1, b: 2}, {b: 42}, {c: 3}, {c: 4}), {a: 1, b: 42, c: 4}, 'should merge three or more objects'); + assert.deepEqual(_.merge(o), {a: 1, b: 2}, 'should return a copy of the object if given only one'); + assert.deepEqual(_.merge({'a': 1, 'b': 2}, {b: 42}), {'a': 1, b: 42}, 'should merge two objects'); + assert.deepEqual(_.merge({a: 1, b: 2}, {b: 42}, {c: 3}), {a: 1, b: 42, c: 3}, 'should merge three or more objects'); + assert.deepEqual(_.merge({a: 1, b: 2}, {b: 42}, {c: 3}, {c: 4}), {a: 1, b: 42, c: 4}, 'should merge three or more objects'); var a = {'a': 1, 'b': 2}; var $ = _.merge(a, {'a': 42}); - deepEqual(a, {'a': 1, 'b': 2}, 'should not modify the original'); + assert.deepEqual(a, {'a': 1, 'b': 2}, 'should not modify the original'); }); - test("renameKeys", function() { - deepEqual(_.renameKeys({'a': 1, 'b': 2}, {'a': 'A'}), {'b': 2, 'A': 1}, 'should rename the keys in the first object to the mapping in the second object'); + QUnit.test("renameKeys", function(assert) { + assert.deepEqual(_.renameKeys({'a': 1, 'b': 2}, {'a': 'A'}), {'b': 2, 'A': 1}, 'should rename the keys in the first object to the mapping in the second object'); var a = {'a': 1, 'b': 2}; var $ = _.renameKeys(a, {'a': 'A'}); - deepEqual(a, {'a': 1, 'b': 2}, 'should not modify the original'); + assert.deepEqual(a, {'a': 1, 'b': 2}, 'should not modify the original'); }); - test("snapshot", function() { + QUnit.test("snapshot", function(assert) { var o = {'a': 1, 'b': 2}; var oSnap = _.snapshot(o); @@ -39,44 +39,154 @@ $(document).ready(function() { var cSnap = _.snapshot(c); c[1].b = 42; - deepEqual(o, oSnap, 'should create a deep copy of an object'); - deepEqual(a, aSnap, 'should create a deep copy of an array'); - deepEqual(n, nSnap, 'should create a deep copy of an array'); - deepEqual(nSnap, [1,{a: 1, b: [1,2,3]},{},4], 'should allow changes to the original to not change copies'); + assert.deepEqual(o, oSnap, 'should create a deep copy of an object'); + assert.deepEqual(a, aSnap, 'should create a deep copy of an array'); + assert.deepEqual(n, nSnap, 'should create a deep copy of an array'); + assert.deepEqual(nSnap, [1,{a: 1, b: [1,2,3]},{},4], 'should allow changes to the original to not change copies'); }); - test("setPath", function() { + QUnit.test("setPath", function(assert) { var obj = {a: {b: {c: 42, d: 108}}}; var ary = ['a', ['b', ['c', 'd'], 'e']]; var nest = [1, {a: 2, b: [3,4], c: 5}, 6]; - deepEqual(_.setPath(obj, 9, ['a', 'b', 'c']), {a: {b: {c: 9, d: 108}}}, ''); - deepEqual(_.setPath(ary, 9, [1, 1, 0]), ['a', ['b', [9, 'd'], 'e']], ''); - deepEqual(_.setPath(nest, 9, [1, 'b', 1]), [1, {a: 2, b: [3,9], c: 5}, 6], ''); + assert.deepEqual(_.setPath(obj, 9, ['a', 'b', 'c']), {a: {b: {c: 9, d: 108}}}, ''); + assert.deepEqual(_.setPath(ary, 9, [1, 1, 0]), ['a', ['b', [9, 'd'], 'e']], ''); + assert.deepEqual(_.setPath(nest, 9, [1, 'b', 1]), [1, {a: 2, b: [3,9], c: 5}, 6], ''); - deepEqual(_.setPath(obj, 9, 'a'), {a: 9}, ''); - deepEqual(_.setPath(ary, 9, 1), ['a', 9], ''); + assert.deepEqual(_.setPath(obj, 9, 'a'), {a: 9}, ''); + assert.deepEqual(_.setPath(ary, 9, 1), ['a', 9], ''); - deepEqual(obj, {a: {b: {c: 42, d: 108}}}, 'should not modify the original object'); - deepEqual(ary, ['a', ['b', ['c', 'd'], 'e']], 'should not modify the original array'); - deepEqual(nest, [1, {a: 2, b: [3,4], c: 5}, 6], 'should not modify the original nested structure'); + assert.deepEqual(obj, {a: {b: {c: 42, d: 108}}}, 'should not modify the original object'); + assert.deepEqual(ary, ['a', ['b', ['c', 'd'], 'e']], 'should not modify the original array'); + assert.deepEqual(nest, [1, {a: 2, b: [3,4], c: 5}, 6], 'should not modify the original nested structure'); }); - test("updatePath", function() { + QUnit.test("updatePath", function(assert) { var obj = {a: {b: {c: 42, d: 108}}}; var ary = ['a', ['b', ['c', 'd'], 'e']]; var nest = [1, {a: 2, b: [3,4], c: 5}, 6]; - deepEqual(_.updatePath(obj, _.always(9), ['a', 'b', 'c']), {a: {b: {c: 9, d: 108}}}, ''); - deepEqual(_.updatePath(ary, _.always(9), [1, 1, 0]), ['a', ['b', [9, 'd'], 'e']], ''); - deepEqual(_.updatePath(nest, _.always(9), [1, 'b', 1]), [1, {a: 2, b: [3,9], c: 5}, 6], ''); + assert.deepEqual(_.updatePath(obj, _.always(9), ['a', 'b', 'c']), {a: {b: {c: 9, d: 108}}}, ''); + assert.deepEqual(_.updatePath(ary, _.always(9), [1, 1, 0]), ['a', ['b', [9, 'd'], 'e']], ''); + assert.deepEqual(_.updatePath(nest, _.always(9), [1, 'b', 1]), [1, {a: 2, b: [3,9], c: 5}, 6], ''); - deepEqual(_.updatePath(obj, _.always(9), 'a'), {a: 9}, ''); - deepEqual(_.updatePath(ary, _.always(9), 1), ['a', 9], ''); + assert.deepEqual(_.updatePath(obj, _.always(9), 'a'), {a: 9}, ''); + assert.deepEqual(_.updatePath(ary, _.always(9), 1), ['a', 9], ''); - deepEqual(obj, {a: {b: {c: 42, d: 108}}}, 'should not modify the original object'); - deepEqual(ary, ['a', ['b', ['c', 'd'], 'e']], 'should not modify the original array'); - deepEqual(nest, [1, {a: 2, b: [3,4], c: 5}, 6], 'should not modify the original nested structure'); + assert.deepEqual(obj, {a: {b: {c: 42, d: 108}}}, 'should not modify the original object'); + assert.deepEqual(ary, ['a', ['b', ['c', 'd'], 'e']], 'should not modify the original array'); + assert.deepEqual(nest, [1, {a: 2, b: [3,4], c: 5}, 6], 'should not modify the original nested structure'); }); + QUnit.test("omitPath", function(assert){ + var a = { + foo: true, + bar: false, + baz: 42, + dada: { + carlos: { pepe: 9 }, + pedro: 'pedro', + list: [ + {file: '..', more: {other: { a: 1, b: 2}}, name: 'aa'}, + {file: '..', name: 'bb'} + ] + } + }; + + assert.deepEqual(_.omitPath(a, 'dada.carlos.pepe'), { + foo: true, + bar: false, + baz: 42, + dada: { + carlos: {}, + pedro: 'pedro', + list: [ + {file: '..', more: {other: { a: 1, b: 2}} , name: 'aa'}, + {file: '..', name: 'bb'} + ] + } + }, "should return an object without the value that represent the path"); + + assert.deepEqual(_.omitPath(a, 'dada.carlos'), { + foo: true, + bar: false, + baz: 42, + dada: { + pedro: 'pedro', + list: [ + {file: '..', more: {other: { a: 1, b: 2}} , name: 'aa'}, + {file: '..', name: 'bb'} + ] + } + }, "should return an object without the value that represent the path"); + + assert.deepEqual(_.omitPath(a, ''), { + foo: true, + bar: false, + baz: 42, + dada: { + carlos: { pepe: 9 }, + pedro: 'pedro', + list: [ + {file: '..', more: {other: { a: 1, b: 2}} , name: 'aa'}, + {file: '..', name: 'bb'} + ] + } + }, "should return the whole object because the path is empty"); + + assert.deepEqual(_.omitPath(a, 'dada.list.0.file'), { + foo: true, + bar: false, + baz: 42, + dada: { + carlos: { pepe: 9 }, + pedro: 'pedro', + list: [ + {name: 'aa', more: {other: { a: 1, b: 2}}}, + {file: '..', name: 'bb'} + ] + } + }, "should return an object without the value in an element of the list"); + + assert.deepEqual(_.omitPath(a, 'dada.list.1.name'), { + foo: true, + bar: false, + baz: 42, + dada: { + carlos: { pepe: 9 }, + pedro: 'pedro', + list: [ + {name: 'aa', file: '..', more: {other: { a: 1, b: 2}}}, + {file: '..'} + ] + } + }, "should return an object without the value in each object of the list"); + + assert.deepEqual(_.omitPath(a, 'dada.list'), { + foo: true, + bar: false, + baz: 42, + dada: { + carlos: { pepe: 9 }, + pedro: 'pedro' + } + }, "should return an object without the list"); + + assert.deepEqual(_.omitPath(a, 'dada.list.0.more.other.a'), { + foo: true, + bar: false, + baz: 42, + dada: { + carlos: { pepe: 9 }, + pedro: 'pedro', + list: [ + {file: '..', more: {other: { b: 2}} , name: 'aa'}, + {file: '..', name: 'bb'} + ] + } + }, + "should return an object without the value inside the values of the list" + ); + }); }); diff --git a/test/object.selectors.js b/test/object.selectors.js index d41fb23..8cd0c1b 100644 --- a/test/object.selectors.js +++ b/test/object.selectors.js @@ -1,110 +1,110 @@ $(document).ready(function() { - module("underscore.object.selectors"); + QUnit.module("underscore.object.selectors"); - test("accessor", function() { + QUnit.test("accessor", function(assert) { var a = [{a: 1, b: 2}, {c: 3}]; - equal(_.accessor('a')(a[0]), 1, 'should return a function that plucks'); - equal(_.accessor('a')(a[1]), undefined, 'should return a function that plucks, or returns undefined'); - deepEqual(_.map(a, _.accessor('a')), [1, undefined], 'should return a function that plucks'); + assert.equal(_.accessor('a')(a[0]), 1, 'should return a function that plucks'); + assert.equal(_.accessor('a')(a[1]), undefined, 'should return a function that plucks, or returns undefined'); + assert.deepEqual(_.map(a, _.accessor('a')), [1, undefined], 'should return a function that plucks'); }); - test("dictionary", function() { + QUnit.test("dictionary", function(assert) { var a = [{a: 1, b: 2}, {c: 3}]; - equal(_.dictionary(a[0])('a'), 1, 'should return a function that acts as a dictionary'); - equal(_.dictionary(a[1])('a'), undefined, 'should return a function that acts as a dictionary, or returns undefined'); + assert.equal(_.dictionary(a[0])('a'), 1, 'should return a function that acts as a dictionary'); + assert.equal(_.dictionary(a[1])('a'), undefined, 'should return a function that acts as a dictionary, or returns undefined'); }); - test("selectKeys", function() { - deepEqual(_.selectKeys({'a': 1, 'b': 2}, ['a']), {'a': 1}, 'shold return a map of the desired keys'); - deepEqual(_.selectKeys({'a': 1, 'b': 2}, ['z']), {}, 'shold return an empty map if the desired keys are not present'); + QUnit.test("selectKeys", function(assert) { + assert.deepEqual(_.selectKeys({'a': 1, 'b': 2}, ['a']), {'a': 1}, 'shold return a map of the desired keys'); + assert.deepEqual(_.selectKeys({'a': 1, 'b': 2}, ['z']), {}, 'shold return an empty map if the desired keys are not present'); }); - test("kv", function() { - deepEqual(_.kv({'a': 1, 'b': 2}, 'a'), ['a', 1], 'should return the key/value pair at the desired key'); - equal(_.kv({'a': 1, 'b': 2}, 'z'), undefined, 'shold return undefined if the desired key is not present'); + QUnit.test("kv", function(assert) { + assert.deepEqual(_.kv({'a': 1, 'b': 2}, 'a'), ['a', 1], 'should return the key/value pair at the desired key'); + assert.equal(_.kv({'a': 1, 'b': 2}, 'z'), undefined, 'shold return undefined if the desired key is not present'); }); - test("getPath", function() { + QUnit.test("getPath", function(assert) { var deepObject = { a: { b: { c: "c" } }, falseVal: false, nullVal: null, undefinedVal: undefined, arrayVal: ["arr"], deepArray: { contents: ["da1", "da2"] } }; var weirdObject = { "D'artagnan": { "[0].[1]": "myValue" }, element: { "0": { "prop.1": "value1" } } }; var deepArr = [[["thirdLevel"]]]; var ks = ["a", "b", "c"]; - strictEqual(_.getPath(deepObject, ks), "c", "should get a deep property's value from objects"); - deepEqual(ks, ["a", "b", "c"], "should not have mutated ks argument"); - strictEqual(_.getPath(deepArr, [0, 0, 0]), "thirdLevel", "should get a deep property's value from arrays"); - strictEqual(_.getPath(deepObject, ["arrayVal", 0]), "arr", "should get a deep property's value from nested arrays and objects"); - strictEqual(_.getPath(deepObject, ["deepArray", "contents", 1]), "da2", "should get a deep property's value within arrays inside deep objects, from an array"); - strictEqual(_.getPath(deepObject, "deepArray.contents[0]"), "da1", "should get a deep property's value within arrays inside deep objects, from a complete javascript path"); + assert.strictEqual(_.getPath(deepObject, ks), "c", "should get a deep property's value from objects"); + assert.deepEqual(ks, ["a", "b", "c"], "should not have mutated ks argument"); + assert.strictEqual(_.getPath(deepArr, [0, 0, 0]), "thirdLevel", "should get a deep property's value from arrays"); + assert.strictEqual(_.getPath(deepObject, ["arrayVal", 0]), "arr", "should get a deep property's value from nested arrays and objects"); + assert.strictEqual(_.getPath(deepObject, ["deepArray", "contents", 1]), "da2", "should get a deep property's value within arrays inside deep objects, from an array"); + assert.strictEqual(_.getPath(deepObject, "deepArray.contents[0]"), "da1", "should get a deep property's value within arrays inside deep objects, from a complete javascript path"); - strictEqual(_.getPath(deepObject, ["undefinedVal"]), undefined, "should return undefined for undefined properties"); - strictEqual(_.getPath(deepObject, ["a", "notHere"]), undefined, "should return undefined for non-existent properties"); - strictEqual(_.getPath(deepObject, ["nullVal"]), null, "should return null for null properties"); - strictEqual(_.getPath(deepObject, ["nullVal", "notHere", "notHereEither"]), undefined, "should return undefined for non-existent descendents of null properties"); + assert.strictEqual(_.getPath(deepObject, ["undefinedVal"]), undefined, "should return undefined for undefined properties"); + assert.strictEqual(_.getPath(deepObject, ["a", "notHere"]), undefined, "should return undefined for non-existent properties"); + assert.strictEqual(_.getPath(deepObject, ["nullVal"]), null, "should return null for null properties"); + assert.strictEqual(_.getPath(deepObject, ["nullVal", "notHere", "notHereEither"]), undefined, "should return undefined for non-existent descendents of null properties"); - strictEqual(_.getPath(weirdObject, ["D'artagnan", "[0].[1]"]), "myValue", "should be able to traverse complex property names, from an array"); - strictEqual(_.getPath(weirdObject, "[\"D'artagnan\"]['[0].[1]']"), "myValue", "should be able to traverse complex property names, from an accessor string"); - strictEqual(_.getPath(weirdObject, "element[0]['prop.1']"), "value1", "should be able to traverse complex property names, from an accessor string"); + assert.strictEqual(_.getPath(weirdObject, ["D'artagnan", "[0].[1]"]), "myValue", "should be able to traverse complex property names, from an array"); + assert.strictEqual(_.getPath(weirdObject, "[\"D'artagnan\"]['[0].[1]']"), "myValue", "should be able to traverse complex property names, from an accessor string"); + assert.strictEqual(_.getPath(weirdObject, "element[0]['prop.1']"), "value1", "should be able to traverse complex property names, from an accessor string"); - strictEqual(_.getPath(deepObject, "a.b.c"), "c", "should work with keys written in dot notation"); - strictEqual(_.getPath({}, "myPath.deepProperty"), undefined, "should not break with empty objects and deep paths"); + assert.strictEqual(_.getPath(deepObject, "a.b.c"), "c", "should work with keys written in dot notation"); + assert.strictEqual(_.getPath({}, "myPath.deepProperty"), undefined, "should not break with empty objects and deep paths"); }); - test("hasPath", function() { + QUnit.test("hasPath", function(assert) { var deepObject = { a: { b: { c: "c" } }, falseVal: false, nullVal: null, undefinedVal: undefined, arrayVal: ["arr"], deepArray: { contents: ["da1", "da2"] } }; var weirdObject = { "D'artagnan": { "[0].[1]": "myValue" }, element: { "0": { "prop.1": "value1" } } }; var ks = ["a", "b", "c"]; - strictEqual(_.hasPath(deepObject, ["notHere", "notHereEither"]), false, "should return false if the path doesn't exist"); - strictEqual(_.hasPath(deepObject, ks), true, "should return true if the path exists"); - deepEqual(ks, ["a", "b", "c"], "should not have mutated ks argument"); + assert.strictEqual(_.hasPath(deepObject, ["notHere", "notHereEither"]), false, "should return false if the path doesn't exist"); + assert.strictEqual(_.hasPath(deepObject, ks), true, "should return true if the path exists"); + assert.deepEqual(ks, ["a", "b", "c"], "should not have mutated ks argument"); - strictEqual(_.hasPath(deepObject, ["deepArray", "contents", 1]), true, "should return true for an existing value within arrays inside deep objects, from an array"); + assert.strictEqual(_.hasPath(deepObject, ["deepArray", "contents", 1]), true, "should return true for an existing value within arrays inside deep objects, from an array"); - strictEqual(_.hasPath(deepObject, ["arrayVal", 0]), true, "should return true for an array's index if it is defined"); - strictEqual(_.hasPath(deepObject, ["arrayVal", 999]), false, "should return false for an array's index if it is not defined"); + assert.strictEqual(_.hasPath(deepObject, ["arrayVal", 0]), true, "should return true for an array's index if it is defined"); + assert.strictEqual(_.hasPath(deepObject, ["arrayVal", 999]), false, "should return false for an array's index if it is not defined"); - strictEqual(_.hasPath(deepObject, ["nullVal"]), true, "should return true for null properties"); - strictEqual(_.hasPath(deepObject, ["undefinedVal"]), true, "should return true for properties that were explicitly assigned undefined"); + assert.strictEqual(_.hasPath(deepObject, ["nullVal"]), true, "should return true for null properties"); + assert.strictEqual(_.hasPath(deepObject, ["undefinedVal"]), true, "should return true for properties that were explicitly assigned undefined"); - strictEqual(_.hasPath(weirdObject, ["D'artagnan", "[0].[1]"]), true, "should return true for complex property names, from an array"); - strictEqual(_.hasPath(weirdObject, "[\"D'artagnan\"]['[0].[1]']"), true, "should return true for complex property names, from an accessor string"); - strictEqual(_.hasPath(weirdObject, "element[0]['prop.1']"), true, "should be return true for complex property names, from an accessor string"); - strictEqual(_.hasPath(weirdObject, ["D'artagnan", "[0].[2]"]), false, "should return false for non-existent complex property names, from an array"); - strictEqual(_.hasPath(weirdObject, "[\"D'artagnan\"]['[0].[2]']"), false, "should return true for non-existent complex property names, from an accessor string"); - strictEqual(_.hasPath(weirdObject, "element[0]['prop.2']"), false, "should be return true for non-existent complex property names, from an accessor string"); + assert.strictEqual(_.hasPath(weirdObject, ["D'artagnan", "[0].[1]"]), true, "should return true for complex property names, from an array"); + assert.strictEqual(_.hasPath(weirdObject, "[\"D'artagnan\"]['[0].[1]']"), true, "should return true for complex property names, from an accessor string"); + assert.strictEqual(_.hasPath(weirdObject, "element[0]['prop.1']"), true, "should be return true for complex property names, from an accessor string"); + assert.strictEqual(_.hasPath(weirdObject, ["D'artagnan", "[0].[2]"]), false, "should return false for non-existent complex property names, from an array"); + assert.strictEqual(_.hasPath(weirdObject, "[\"D'artagnan\"]['[0].[2]']"), false, "should return true for non-existent complex property names, from an accessor string"); + assert.strictEqual(_.hasPath(weirdObject, "element[0]['prop.2']"), false, "should be return true for non-existent complex property names, from an accessor string"); - strictEqual(_.hasPath(deepObject, ["nullVal", "notHere"]), false, "should return false for descendants of null properties"); - strictEqual(_.hasPath(deepObject, ["undefinedVal", "notHere"]), false, "should return false for descendants of undefined properties"); + assert.strictEqual(_.hasPath(deepObject, ["nullVal", "notHere"]), false, "should return false for descendants of null properties"); + assert.strictEqual(_.hasPath(deepObject, ["undefinedVal", "notHere"]), false, "should return false for descendants of undefined properties"); - strictEqual(_.hasPath(deepObject, "a.b.c"), true, "should work with keys written in dot notation."); + assert.strictEqual(_.hasPath(deepObject, "a.b.c"), true, "should work with keys written in dot notation."); - strictEqual(_.hasPath(null, []), true, "should return true for null and undefined when passed no keys"); - strictEqual(_.hasPath(void 0, []), true); - strictEqual(_.hasPath(null, ['']), false, "should return false (not throw) on null/undefined given keys"); - strictEqual(_.hasPath(void 0, ['']), false); + assert.strictEqual(_.hasPath(null, []), true, "should return true for null and undefined when passed no keys"); + assert.strictEqual(_.hasPath(void 0, []), true); + assert.strictEqual(_.hasPath(null, ['']), false, "should return false (not throw) on null/undefined given keys"); + assert.strictEqual(_.hasPath(void 0, ['']), false); - strictEqual(_.hasPath(deepObject, "a.b.c.d"), false, "should return false for keys which doesn't exist on nested existing objects"); + assert.strictEqual(_.hasPath(deepObject, "a.b.c.d"), false, "should return false for keys which doesn't exist on nested existing objects"); }); - test("keysFromPath", function() { - deepEqual(_.keysFromPath("a.b.c"), ["a", "b", "c"], "should convert a path into an array of keys"); - deepEqual(_.keysFromPath("a[0].b['c']"), ["a", "0", "b", "c"], "should handle bracket notation"); - deepEqual(_.keysFromPath("[\"D'artagnan\"]['[0].[1]']"), ["D'artagnan", "[0].[1]"], "should handle complex paths"); + QUnit.test("keysFromPath", function(assert) { + assert.deepEqual(_.keysFromPath("a.b.c"), ["a", "b", "c"], "should convert a path into an array of keys"); + assert.deepEqual(_.keysFromPath("a[0].b['c']"), ["a", "0", "b", "c"], "should handle bracket notation"); + assert.deepEqual(_.keysFromPath("[\"D'artagnan\"]['[0].[1]']"), ["D'artagnan", "[0].[1]"], "should handle complex paths"); }); - test("pickWhen", function() { + QUnit.test("pickWhen", function(assert) { var a = {foo: true, bar: false, baz: 42}; - deepEqual(_.pickWhen(a, _.truthy), {foo: true, baz: 42}, "should return an object with kvs that return a truthy value for the given predicate"); + assert.deepEqual(_.pickWhen(a, _.truthy), {foo: true, baz: 42}, "should return an object with kvs that return a truthy value for the given predicate"); }); - test("omitWhen", function() { + QUnit.test("omitWhen", function(assert) { var a = {foo: [], bar: "", baz: "something", quux: ['a']}; - deepEqual(_.omitWhen(a, _.isEmpty), {baz: "something", quux: ['a']}, "should return an object with kvs that return a falsey value for the given predicate"); + assert.deepEqual(_.omitWhen(a, _.isEmpty), {baz: "something", quux: ['a']}, "should return an object with kvs that return a falsey value for the given predicate"); }); }); diff --git a/test/util.existential.js b/test/util.existential.js index 82eaf6a..2136d90 100644 --- a/test/util.existential.js +++ b/test/util.existential.js @@ -1,63 +1,63 @@ $(document).ready(function() { - module("underscore.util.existential"); - - test("exists", function() { - equal(_.exists(null), false, 'should know that null is not existy'); - equal(_.exists(undefined), false, 'should know that undefined is not existy'); - - equal(_.exists(1), true, 'should know that all but null and undefined are existy'); - equal(_.exists(0), true, 'should know that all but null and undefined are existy'); - equal(_.exists(-1), true, 'should know that all but null and undefined are existy'); - equal(_.exists(3.14), true, 'should know that all but null and undefined are existy'); - equal(_.exists('undefined'), true, 'should know that all but null and undefined are existy'); - equal(_.exists(''), true, 'should know that all but null and undefined are existy'); - equal(_.exists(NaN), true, 'should know that all but null and undefined are existy'); - equal(_.exists(Infinity), true, 'should know that all but null and undefined are existy'); - equal(_.exists(true), true, 'should know that all but null and undefined are existy'); - equal(_.exists(false), true, 'should know that all but null and undefined are existy'); - equal(_.exists(function(){}), true, 'should know that all but null and undefined are existy'); + QUnit.module("underscore.util.existential"); + + QUnit.test("exists", function(assert) { + assert.equal(_.exists(null), false, 'should know that null is not existy'); + assert.equal(_.exists(undefined), false, 'should know that undefined is not existy'); + + assert.equal(_.exists(1), true, 'should know that all but null and undefined are existy'); + assert.equal(_.exists(0), true, 'should know that all but null and undefined are existy'); + assert.equal(_.exists(-1), true, 'should know that all but null and undefined are existy'); + assert.equal(_.exists(3.14), true, 'should know that all but null and undefined are existy'); + assert.equal(_.exists('undefined'), true, 'should know that all but null and undefined are existy'); + assert.equal(_.exists(''), true, 'should know that all but null and undefined are existy'); + assert.equal(_.exists(NaN), true, 'should know that all but null and undefined are existy'); + assert.equal(_.exists(Infinity), true, 'should know that all but null and undefined are existy'); + assert.equal(_.exists(true), true, 'should know that all but null and undefined are existy'); + assert.equal(_.exists(false), true, 'should know that all but null and undefined are existy'); + assert.equal(_.exists(function(){}), true, 'should know that all but null and undefined are existy'); }); - test("truthy", function() { - equal(_.truthy(null), false, 'should know that null, undefined and false are not truthy'); - equal(_.truthy(undefined), false, 'should know that null, undefined and false are not truthy'); - equal(_.truthy(false), false, 'should know that null, undefined and false are not truthy'); - - equal(_.truthy(1), true, 'should know that everything else is truthy'); - equal(_.truthy(0), true, 'should know that everything else is truthy'); - equal(_.truthy(-1), true, 'should know that everything else is truthy'); - equal(_.truthy(3.14), true, 'should know that everything else is truthy'); - equal(_.truthy('undefined'), true, 'should know that everything else is truthy'); - equal(_.truthy(''), true, 'should know that everything else is truthy'); - equal(_.truthy(NaN), true, 'should know that everything else is truthy'); - equal(_.truthy(Infinity), true, 'should know that everything else is truthy'); - equal(_.truthy(true), true, 'should know that everything else is truthy'); - equal(_.truthy(function(){}), true, 'should know that everything else is truthy'); + QUnit.test("truthy", function(assert) { + assert.equal(_.truthy(null), false, 'should know that null, undefined and false are not truthy'); + assert.equal(_.truthy(undefined), false, 'should know that null, undefined and false are not truthy'); + assert.equal(_.truthy(false), false, 'should know that null, undefined and false are not truthy'); + + assert.equal(_.truthy(1), true, 'should know that everything else is truthy'); + assert.equal(_.truthy(0), true, 'should know that everything else is truthy'); + assert.equal(_.truthy(-1), true, 'should know that everything else is truthy'); + assert.equal(_.truthy(3.14), true, 'should know that everything else is truthy'); + assert.equal(_.truthy('undefined'), true, 'should know that everything else is truthy'); + assert.equal(_.truthy(''), true, 'should know that everything else is truthy'); + assert.equal(_.truthy(NaN), true, 'should know that everything else is truthy'); + assert.equal(_.truthy(Infinity), true, 'should know that everything else is truthy'); + assert.equal(_.truthy(true), true, 'should know that everything else is truthy'); + assert.equal(_.truthy(function(){}), true, 'should know that everything else is truthy'); }); - test("falsey", function() { - equal(_.falsey(null), true, 'should know that null, undefined and false are not falsey'); - equal(_.falsey(undefined), true, 'should know that null, undefined and false are not falsey'); - equal(_.falsey(false), true, 'should know that null, undefined and false are not falsey'); - - equal(_.falsey(1), false, 'should know that everything else is falsey'); - equal(_.falsey(0), false, 'should know that everything else is falsey'); - equal(_.falsey(-1), false, 'should know that everything else is falsey'); - equal(_.falsey(3.14), false, 'should know that everything else is falsey'); - equal(_.falsey('undefined'), false, 'should know that everything else is falsey'); - equal(_.falsey(''), false, 'should know that everything else is falsey'); - equal(_.falsey(NaN), false, 'should know that everything else is falsey'); - equal(_.falsey(Infinity), false, 'should know that everything else is falsey'); - equal(_.falsey(true), false, 'should know that everything else is falsey'); - equal(_.falsey(function(){}), false, 'should know that everything else is falsey'); + QUnit.test("falsey", function(assert) { + assert.equal(_.falsey(null), true, 'should know that null, undefined and false are not falsey'); + assert.equal(_.falsey(undefined), true, 'should know that null, undefined and false are not falsey'); + assert.equal(_.falsey(false), true, 'should know that null, undefined and false are not falsey'); + + assert.equal(_.falsey(1), false, 'should know that everything else is falsey'); + assert.equal(_.falsey(0), false, 'should know that everything else is falsey'); + assert.equal(_.falsey(-1), false, 'should know that everything else is falsey'); + assert.equal(_.falsey(3.14), false, 'should know that everything else is falsey'); + assert.equal(_.falsey('undefined'), false, 'should know that everything else is falsey'); + assert.equal(_.falsey(''), false, 'should know that everything else is falsey'); + assert.equal(_.falsey(NaN), false, 'should know that everything else is falsey'); + assert.equal(_.falsey(Infinity), false, 'should know that everything else is falsey'); + assert.equal(_.falsey(true), false, 'should know that everything else is falsey'); + assert.equal(_.falsey(function(){}), false, 'should know that everything else is falsey'); }); - test('firstExisting', function() { - equal(_.firstExisting('first', 'second'), 'first', 'should return the first existing value'); - equal(_.firstExisting(null, 'second'), 'second', 'should ignore null'); - equal(_.firstExisting(void 0, 'second'), 'second', 'should ignore undefined'); - equal(_.firstExisting(null, void 0, 'third'), 'third', 'should work with more arguments'); + QUnit.test('firstExisting', function(assert) { + assert.equal(_.firstExisting('first', 'second'), 'first', 'should return the first existing value'); + assert.equal(_.firstExisting(null, 'second'), 'second', 'should ignore null'); + assert.equal(_.firstExisting(void 0, 'second'), 'second', 'should ignore undefined'); + assert.equal(_.firstExisting(null, void 0, 'third'), 'third', 'should work with more arguments'); }); }); diff --git a/test/util.operators.js b/test/util.operators.js index f0c4873..fed5042 100644 --- a/test/util.operators.js +++ b/test/util.operators.js @@ -1,159 +1,159 @@ $(document).ready(function() { - module("underscore.util.operators"); + QUnit.module("underscore.util.operators"); - test("add", function() { - equal(_.add(1, 1), 2, '1 + 1 = 2'); - equal(_.add(3, 5), 8, '3 + 5 = 8'); - equal(_.add(1, 2, 3, 4), 10, 'adds multiple operands'); - equal(_.add([1, 2, 3, 4]), 10, 'adds multiple operands, when specified in an array'); + QUnit.test("add", function(assert) { + assert.equal(_.add(1, 1), 2, '1 + 1 = 2'); + assert.equal(_.add(3, 5), 8, '3 + 5 = 8'); + assert.equal(_.add(1, 2, 3, 4), 10, 'adds multiple operands'); + assert.equal(_.add([1, 2, 3, 4]), 10, 'adds multiple operands, when specified in an array'); }); - test("sub", function() { - equal(_.sub(1, 1), 0, '1 - 1 = 0'); - equal(_.sub(5, 3), 2, '5 - 3 = 2'); - equal(_.sub(10, 9, 8, 7), -14, 'subtracts multiple operands'); - equal(_.sub([10, 9, 8, 7]), -14, 'subtracts multiple operands, when specified in an array'); + QUnit.test("sub", function(assert) { + assert.equal(_.sub(1, 1), 0, '1 - 1 = 0'); + assert.equal(_.sub(5, 3), 2, '5 - 3 = 2'); + assert.equal(_.sub(10, 9, 8, 7), -14, 'subtracts multiple operands'); + assert.equal(_.sub([10, 9, 8, 7]), -14, 'subtracts multiple operands, when specified in an array'); }); - test("mul", function() { - equal(_.mul(1, 1), 1, '1 * 1 = 1'); - equal(_.mul(5, 3), 15, '5 * 3 = 15'); - equal(_.mul(1, 2, 3, 4), 24, 'multiplies multiple operands'); - equal(_.mul([1, 2, 3, 4]), 24, 'multiplies multiple operands, when specified in an array'); + QUnit.test("mul", function(assert) { + assert.equal(_.mul(1, 1), 1, '1 * 1 = 1'); + assert.equal(_.mul(5, 3), 15, '5 * 3 = 15'); + assert.equal(_.mul(1, 2, 3, 4), 24, 'multiplies multiple operands'); + assert.equal(_.mul([1, 2, 3, 4]), 24, 'multiplies multiple operands, when specified in an array'); }); - test("div", function() { - equal(_.div(1, 1), 1, '1 / 1 = 1'); - equal(_.div(15, 3), 5, '15 / 3 = 5'); - equal(_.div(15, 0), Infinity, '15 / 0 = Infinity'); - equal(_.div(24, 2, 2, 2), 3, 'divides multiple operands'); - equal(_.div([24, 2, 2, 2]), 3, 'divides multiple operands, when specified in an array'); + QUnit.test("div", function(assert) { + assert.equal(_.div(1, 1), 1, '1 / 1 = 1'); + assert.equal(_.div(15, 3), 5, '15 / 3 = 5'); + assert.equal(_.div(15, 0), Infinity, '15 / 0 = Infinity'); + assert.equal(_.div(24, 2, 2, 2), 3, 'divides multiple operands'); + assert.equal(_.div([24, 2, 2, 2]), 3, 'divides multiple operands, when specified in an array'); }); - test("mod", function() { - equal(_.mod(3, 2), 1, '3 / 2 = 1'); - equal(_.mod(15, 3), 0, '15 / 3 = 0'); + QUnit.test("mod", function(assert) { + assert.equal(_.mod(3, 2), 1, '3 / 2 = 1'); + assert.equal(_.mod(15, 3), 0, '15 / 3 = 0'); }); - test("inc", function() { - equal(_.inc(1), 2, '++1 = 2'); - equal(_.inc(15), 16, '++15 = 16'); + QUnit.test("inc", function(assert) { + assert.equal(_.inc(1), 2, '++1 = 2'); + assert.equal(_.inc(15), 16, '++15 = 16'); }); - test("dec", function() { - equal(_.dec(2), 1, '--2 = 1'); - equal(_.dec(15), 14, '--15 = 15'); + QUnit.test("dec", function(assert) { + assert.equal(_.dec(2), 1, '--2 = 1'); + assert.equal(_.dec(15), 14, '--15 = 15'); }); - test("neg", function() { - equal(_.neg(2), -2, 'opposite of 2'); - equal(_.neg(-2), 2, 'opposite of -2'); - equal(_.neg(true), -1, 'opposite of true'); + QUnit.test("neg", function(assert) { + assert.equal(_.neg(2), -2, 'opposite of 2'); + assert.equal(_.neg(-2), 2, 'opposite of -2'); + assert.equal(_.neg(true), -1, 'opposite of true'); }); - test("eq", function() { - equal(_.eq(1, 1), true, '1 == 1'); - equal(_.eq(1, true), true, '1 == true'); - equal(_.eq(1, false), false, '1 != false'); - equal(_.eq(1, '1'), true, '1 == "1"'); - equal(_.eq(1, 'one'), false, '1 != "one"'); - equal(_.eq(0, 0), true, '0 == 0'); - equal(_.eq(0, false), true, '0 == false'); - equal(_.eq(0, '0'), true, '0 == "0"'); - equal(_.eq({}, {}), false, '{} == {}'); - equal(false, false, 'failing placeholder'); - equal(_.eq(0, 0, 1), false, 'compares a list of arguments'); - equal(_.eq([0, 0, 1]), false, 'compares a list of arguments, when specified as an array'); - }); - test("seq", function() { - equal(_.seq(1, 1), true, '1 === 1'); - equal(_.seq(1, '1'), false, '1 !== "1"'); - equal(_.seq(0, 0, 1), false, 'compares a list of arguments'); - equal(_.seq([0, 0, 1]), false, 'compares a list of arguments, when specified as an array'); - }); - test("neq", function() { - equal(_.neq('a', 'b'), true, '"a" != "b"'); - equal(_.neq(1, '1'), false, '1 == "1"'); - equal(_.neq(0, 0, 1), true, 'compares a list of arguments'); - equal(_.neq([0, 0, 1]), true, 'compares a list of arguments, when specified as an array'); - }); - test("sneq", function() { - equal(_.sneq('a', 'b'), true, '"a" !== "b"'); - equal(_.sneq(1, '1'), true, '1 !== "1"'); - equal(_.sneq(0, 0, 1), true, 'compares a list of arguments'); - equal(_.sneq([0, 0, 1]), true, 'compares a list of arguments, when specified as an array'); - }); - test("not", function() { - equal(_.not(true), false, 'converts true to false'); - equal(_.not(false), true, 'converts false to true'); - equal(_.not('truthy'), false, 'converts truthy values to false'); - equal(_.not(null), true, 'converts falsy values to true'); - }); - test("gt", function() { - equal(_.gt(3, 2), true, '3 > 2'); - equal(_.gt(1, 3), false, '1 > 3'); - equal(_.gt(1, 2, 1), false, 'compares a list of arguments'); - equal(_.gt([1, 2, 1]), false, 'compares a list of arguments, when specified as an array'); - }); - test("lt", function() { - equal(_.lt(3, 2), false, '3 < 2'); - equal(_.lt(1, 3), true, '1 < 3'); - equal(_.lt(1, 2, 1), false, 'compares a list of arguments'); - equal(_.lt([1, 2, 1]), false, 'compares a list of arguments, when specified as an array'); - }); - test("gte", function() { - equal(_.gte(3, 2), true, '3 >= 2'); - equal(_.gte(1, 3), false, '1 >= 3'); - equal(_.gte(3, 3), true, '3 >= 3'); - equal(_.gte(2, 3, 1), false, 'compares a list of arguments'); - equal(_.gte([2, 3, 1]), false, 'compares a list of arguments, when specified as an array'); - }); - test("lte", function() { - equal(_.lte(3, 2), false, '3 <= 2'); - equal(_.lte(1, 3), true, '1 <= 3'); - equal(_.lte(3, 3), true, '3 <= 3'); - equal(_.lte(2, 2, 1), false, 'compares a list of arguments'); - equal(_.lte([2, 2, 1]), false, 'compares a list of arguments, when specified as an array'); - }); - test("bitwiseAnd", function() { - equal(_.bitwiseAnd(1, 1), 1, '1 & 1'); - equal(_.bitwiseAnd(1, 0), 0, '1 & 0'); - equal(_.bitwiseAnd(1, 1, 0), 0, 'operates on multiple arguments'); - equal(_.bitwiseAnd([1, 1, 0]), 0, 'operates on multiple arguments, when specified as an array'); - }); - test("bitwiseOr", function() { - equal(_.bitwiseOr(1, 1), 1, '1 | 1'); - equal(_.bitwiseOr(1, 0), 1, '1 | 0'); - equal(_.bitwiseOr(1, 1, 2), 3, 'operates on multiple arguments'); - equal(_.bitwiseOr([1, 1, 2]), 3, 'operates on multiple arguments, when specified as an array'); - }); - test("bitwiseXor", function() { - equal(_.bitwiseXor(1, 1), 0, '1 ^ 1'); - equal(_.bitwiseXor(1, 2), 3, '1 ^ 2'); - equal(_.bitwiseXor(1, 2, 3), 0, 'operates on multiple arguments'); - equal(_.bitwiseXor([1, 2, 3]), 0, 'operates on multiple arguments, when specified as an array'); - }); - test("bitwiseNot", function() { - equal(_.bitwiseNot(1), -2, '~1'); - equal(_.bitwiseNot(2), -3, '~2'); - }); - test("bitwiseLeft", function() { - equal(_.bitwiseLeft(1, 1), 2, '1 << 1'); - equal(_.bitwiseLeft(1, 0), 1, '1 << 0'); - equal(_.bitwiseLeft(1, 1, 1), 4, 'operates on multiple arguments'); - equal(_.bitwiseLeft([1, 1, 1]), 4, 'operates on multiple arguments, when specified as an array'); - }); - test("bitwiseRight", function() { - equal(_.bitwiseRight(1, 1), 0, '1 >> 1'); - equal(_.bitwiseRight(2, 1), 1, '2 >> 1'); - equal(_.bitwiseRight(3, 1, 1), 0, 'operates on multiple arguments'); - equal(_.bitwiseRight([3, 1, 1]), 0, 'operates on multiple arguments, when specified as an array'); - }); - test("bitwiseZ", function() { - equal(_.bitwiseZ(-1, 1), 2147483647, '-1 >>> 1'); - equal(_.bitwiseZ(-1, 1, 1), 1073741823, 'operates on multiple arguments'); - equal(_.bitwiseZ([-1, 1, 1]), 1073741823, 'operates on multiple arguments, when specified as an array'); + QUnit.test("eq", function(assert) { + assert.equal(_.eq(1, 1), true, '1 == 1'); + assert.equal(_.eq(1, true), true, '1 == true'); + assert.equal(_.eq(1, false), false, '1 != false'); + assert.equal(_.eq(1, '1'), true, '1 == "1"'); + assert.equal(_.eq(1, 'one'), false, '1 != "one"'); + assert.equal(_.eq(0, 0), true, '0 == 0'); + assert.equal(_.eq(0, false), true, '0 == false'); + assert.equal(_.eq(0, '0'), true, '0 == "0"'); + assert.equal(_.eq({}, {}), false, '{} == {}'); + assert.equal(false, false, 'failing placeholder'); + assert.equal(_.eq(0, 0, 1), false, 'compares a list of arguments'); + assert.equal(_.eq([0, 0, 1]), false, 'compares a list of arguments, when specified as an array'); + }); + QUnit.test("seq", function(assert) { + assert.equal(_.seq(1, 1), true, '1 === 1'); + assert.equal(_.seq(1, '1'), false, '1 !== "1"'); + assert.equal(_.seq(0, 0, 1), false, 'compares a list of arguments'); + assert.equal(_.seq([0, 0, 1]), false, 'compares a list of arguments, when specified as an array'); + }); + QUnit.test("neq", function(assert) { + assert.equal(_.neq('a', 'b'), true, '"a" != "b"'); + assert.equal(_.neq(1, '1'), false, '1 == "1"'); + assert.equal(_.neq(0, 0, 1), true, 'compares a list of arguments'); + assert.equal(_.neq([0, 0, 1]), true, 'compares a list of arguments, when specified as an array'); + }); + QUnit.test("sneq", function(assert) { + assert.equal(_.sneq('a', 'b'), true, '"a" !== "b"'); + assert.equal(_.sneq(1, '1'), true, '1 !== "1"'); + assert.equal(_.sneq(0, 0, 1), true, 'compares a list of arguments'); + assert.equal(_.sneq([0, 0, 1]), true, 'compares a list of arguments, when specified as an array'); + }); + QUnit.test("not", function(assert) { + assert.equal(_.not(true), false, 'converts true to false'); + assert.equal(_.not(false), true, 'converts false to true'); + assert.equal(_.not('truthy'), false, 'converts truthy values to false'); + assert.equal(_.not(null), true, 'converts falsy values to true'); + }); + QUnit.test("gt", function(assert) { + assert.equal(_.gt(3, 2), true, '3 > 2'); + assert.equal(_.gt(1, 3), false, '1 > 3'); + assert.equal(_.gt(1, 2, 1), false, 'compares a list of arguments'); + assert.equal(_.gt([1, 2, 1]), false, 'compares a list of arguments, when specified as an array'); + }); + QUnit.test("lt", function(assert) { + assert.equal(_.lt(3, 2), false, '3 < 2'); + assert.equal(_.lt(1, 3), true, '1 < 3'); + assert.equal(_.lt(1, 2, 1), false, 'compares a list of arguments'); + assert.equal(_.lt([1, 2, 1]), false, 'compares a list of arguments, when specified as an array'); + }); + QUnit.test("gte", function(assert) { + assert.equal(_.gte(3, 2), true, '3 >= 2'); + assert.equal(_.gte(1, 3), false, '1 >= 3'); + assert.equal(_.gte(3, 3), true, '3 >= 3'); + assert.equal(_.gte(2, 3, 1), false, 'compares a list of arguments'); + assert.equal(_.gte([2, 3, 1]), false, 'compares a list of arguments, when specified as an array'); + }); + QUnit.test("lte", function(assert) { + assert.equal(_.lte(3, 2), false, '3 <= 2'); + assert.equal(_.lte(1, 3), true, '1 <= 3'); + assert.equal(_.lte(3, 3), true, '3 <= 3'); + assert.equal(_.lte(2, 2, 1), false, 'compares a list of arguments'); + assert.equal(_.lte([2, 2, 1]), false, 'compares a list of arguments, when specified as an array'); + }); + QUnit.test("bitwiseAnd", function(assert) { + assert.equal(_.bitwiseAnd(1, 1), 1, '1 & 1'); + assert.equal(_.bitwiseAnd(1, 0), 0, '1 & 0'); + assert.equal(_.bitwiseAnd(1, 1, 0), 0, 'operates on multiple arguments'); + assert.equal(_.bitwiseAnd([1, 1, 0]), 0, 'operates on multiple arguments, when specified as an array'); + }); + QUnit.test("bitwiseOr", function(assert) { + assert.equal(_.bitwiseOr(1, 1), 1, '1 | 1'); + assert.equal(_.bitwiseOr(1, 0), 1, '1 | 0'); + assert.equal(_.bitwiseOr(1, 1, 2), 3, 'operates on multiple arguments'); + assert.equal(_.bitwiseOr([1, 1, 2]), 3, 'operates on multiple arguments, when specified as an array'); + }); + QUnit.test("bitwiseXor", function(assert) { + assert.equal(_.bitwiseXor(1, 1), 0, '1 ^ 1'); + assert.equal(_.bitwiseXor(1, 2), 3, '1 ^ 2'); + assert.equal(_.bitwiseXor(1, 2, 3), 0, 'operates on multiple arguments'); + assert.equal(_.bitwiseXor([1, 2, 3]), 0, 'operates on multiple arguments, when specified as an array'); + }); + QUnit.test("bitwiseNot", function(assert) { + assert.equal(_.bitwiseNot(1), -2, '~1'); + assert.equal(_.bitwiseNot(2), -3, '~2'); + }); + QUnit.test("bitwiseLeft", function(assert) { + assert.equal(_.bitwiseLeft(1, 1), 2, '1 << 1'); + assert.equal(_.bitwiseLeft(1, 0), 1, '1 << 0'); + assert.equal(_.bitwiseLeft(1, 1, 1), 4, 'operates on multiple arguments'); + assert.equal(_.bitwiseLeft([1, 1, 1]), 4, 'operates on multiple arguments, when specified as an array'); + }); + QUnit.test("bitwiseRight", function(assert) { + assert.equal(_.bitwiseRight(1, 1), 0, '1 >> 1'); + assert.equal(_.bitwiseRight(2, 1), 1, '2 >> 1'); + assert.equal(_.bitwiseRight(3, 1, 1), 0, 'operates on multiple arguments'); + assert.equal(_.bitwiseRight([3, 1, 1]), 0, 'operates on multiple arguments, when specified as an array'); + }); + QUnit.test("bitwiseZ", function(assert) { + assert.equal(_.bitwiseZ(-1, 1), 2147483647, '-1 >>> 1'); + assert.equal(_.bitwiseZ(-1, 1, 1), 1073741823, 'operates on multiple arguments'); + assert.equal(_.bitwiseZ([-1, 1, 1]), 1073741823, 'operates on multiple arguments, when specified as an array'); }); }); diff --git a/test/util.strings.js b/test/util.strings.js index dc7d071..a88c5e3 100644 --- a/test/util.strings.js +++ b/test/util.strings.js @@ -1,15 +1,15 @@ $(document).ready(function() { - module('underscore.util.strings'); + QUnit.module('underscore.util.strings'); - test('explode', function() { - deepEqual(_.explode('Virgil'), ['V','i','r','g','i','l'], 'Should explode a string into an array of characters.'); + QUnit.test('explode', function(assert) { + assert.deepEqual(_.explode('Virgil'), ['V','i','r','g','i','l'], 'Should explode a string into an array of characters.'); }); - test('fromQuery', function() { + QUnit.test('fromQuery', function(assert) { var query = 'foo%5Bbar%5D%5Bbaz%5D%5Bblargl%5D=blah&foo%5Bbar%5D%5Bbaz%5D%5Bblargr%5D=woop&blar=bluh&abc[]=123&abc[]=234'; - ok(_.isEqual(_.fromQuery(query), { + assert.ok(_.isEqual(_.fromQuery(query), { 'foo': { 'bar': { 'baz': { @@ -26,30 +26,33 @@ $(document).ready(function() { }), 'can convert a query string to a hash'); }); - test('implode', function() { - equal(_.implode(['H','o','m','e','r']), 'Homer', 'Should implode an array of characters into a single string.'); + QUnit.test('implode', function(assert) { + assert.equal(_.implode(['H','o','m','e','r']), 'Homer', 'Should implode an array of characters into a single string.'); }); - test('camelCase', function() { - equal(_.camelCase('punic-wars'), 'punicWars', 'Should convert a dashed-format string to camelCase.'); + QUnit.test('camelCase', function(assert) { + assert.equal(_.camelCase('punic-wars'), 'punicWars', 'Should convert a dashed-format string to camelCase.'); }); - test('toDash', function() { - equal(_.toDash('trojanWar'), 'trojan-war', 'Should convert a camelCase string to dashed-format.'); - equal(_.toDash('PersianWar'), 'persian-war', 'Should convert a PascalCase string to dashed-format.'); + QUnit.test('toDash', function(assert) { + assert.equal(_.toDash('trojanWar'), 'trojan-war', 'Should convert a camelCase string to dashed-format.'); + assert.equal(_.toDash('PersianWar'), 'persian-war', 'Should convert a PascalCase string to dashed-format.'); }); - test('toQuery', function() { + QUnit.test('toQuery', function(assert) { var obj = {'foo&bar': 'baz', 'test': 'total success', 'nested': {'works': 'too'}, 'isn\'t': ['that', 'cool?']}; - equal(_.toQuery(obj), 'foo%26bar=baz&test=total+success&nested%5Bworks%5D=too&isn\'t%5B%5D=that&isn\'t%5B%5D=cool%3F', 'can convert a hash to a query string'); - equal(_.toQuery(obj), jQuery.param(obj), 'query serialization matchs jQuery.param()'); + assert.equal(_.toQuery(obj), 'foo%26bar=baz&test=total%20success&nested%5Bworks%5D=too&isn\'t%5B%5D=that&isn\'t%5B%5D=cool%3F', 'can convert a hash to a query string'); + assert.equal(_.toQuery(obj), jQuery.param(obj), 'query serialization matchs jQuery.param()'); + assert.equal(_.toQuery({a: []}), '', 'empty array params produce the empty string'); + assert.equal(_.toQuery({a: [], b: []}), '', 'multiple empty array params do not lead to spurious ampersands'); + assert.equal(_.toQuery({a: null, b: undefined}), 'a=null&b=undefined', 'respects null and undefined'); }); - test('strContains', function() { - equal(_.strContains('Metaphysics', 'physics'), true, 'Should return true if string contains search string.'); - equal(_.strContains('Poetics', 'prose'), false, 'Should return false if string does not contain search string.'); + QUnit.test('strContains', function(assert) { + assert.equal(_.strContains('Metaphysics', 'physics'), true, 'Should return true if string contains search string.'); + assert.equal(_.strContains('Poetics', 'prose'), false, 'Should return false if string does not contain search string.'); var thrower = function() { _.strContains([], ''); }; - throws(thrower, TypeError, 'Throws TypeError if first argument is not a string.'); + assert.throws(thrower, TypeError, 'Throws TypeError if first argument is not a string.'); }); }); diff --git a/test/util.trampolines.js b/test/util.trampolines.js index ae01118..060dcf9 100644 --- a/test/util.trampolines.js +++ b/test/util.trampolines.js @@ -1,8 +1,8 @@ $(document).ready(function() { - module("underscore.util.trampolines"); + QUnit.module("underscore.util.trampolines"); - test("trampoline", function() { + QUnit.test("trampoline", function(assert) { var oddOline = function(n) { if (n === 0) return _.done(false); @@ -17,12 +17,12 @@ $(document).ready(function() { return _.partial(oddOline, Math.abs(n) - 1); }; - equal(_.trampoline(evenOline, 55000), true, 'should trampoline two mutually recursive functions'); - equal(_.trampoline(evenOline, 0), true, 'should trampoline two mutually recursive functions'); - equal(_.trampoline(evenOline, 111111), false, 'should trampoline two mutually recursive functions'); - equal(_.trampoline(oddOline, 1), true, 'should trampoline two mutually recursive functions'); - equal(_.trampoline(oddOline, 11111), true, 'should trampoline two mutually recursive functions'); - equal(_.trampoline(oddOline, 22), false, 'should trampoline two mutually recursive functions'); + assert.equal(_.trampoline(evenOline, 55000), true, 'should trampoline two mutually recursive functions'); + assert.equal(_.trampoline(evenOline, 0), true, 'should trampoline two mutually recursive functions'); + assert.equal(_.trampoline(evenOline, 111111), false, 'should trampoline two mutually recursive functions'); + assert.equal(_.trampoline(oddOline, 1), true, 'should trampoline two mutually recursive functions'); + assert.equal(_.trampoline(oddOline, 11111), true, 'should trampoline two mutually recursive functions'); + assert.equal(_.trampoline(oddOline, 22), false, 'should trampoline two mutually recursive functions'); }); }); diff --git a/test/vendor/jquery.js b/test/vendor/jquery.js deleted file mode 100644 index 3774ff9..0000000 --- a/test/vendor/jquery.js +++ /dev/null @@ -1,9404 +0,0 @@ -/*! - * jQuery JavaScript Library v1.7.2 - * http://jquery.com/ - * - * Copyright 2011, John Resig - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * Includes Sizzle.js - * http://sizzlejs.com/ - * Copyright 2011, The Dojo Foundation - * Released under the MIT, BSD, and GPL Licenses. - * - * Date: Wed Mar 21 12:46:34 2012 -0700 - */ -(function( window, undefined ) { - -// Use the correct document accordingly with window argument (sandbox) -var document = window.document, - navigator = window.navigator, - location = window.location; -var jQuery = (function() { - -// Define a local copy of jQuery -var jQuery = function( selector, context ) { - // The jQuery object is actually just the init constructor 'enhanced' - return new jQuery.fn.init( selector, context, rootjQuery ); - }, - - // Map over jQuery in case of overwrite - _jQuery = window.jQuery, - - // Map over the $ in case of overwrite - _$ = window.$, - - // A central reference to the root jQuery(document) - rootjQuery, - - // A simple way to check for HTML strings or ID strings - // Prioritize #id over to avoid XSS via location.hash (#9521) - quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, - - // Check if a string has a non-whitespace character in it - rnotwhite = /\S/, - - // Used for trimming whitespace - trimLeft = /^\s+/, - trimRight = /\s+$/, - - // Match a standalone tag - rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, - - // JSON RegExp - rvalidchars = /^[\],:{}\s]*$/, - rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, - rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, - rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, - - // Useragent RegExp - rwebkit = /(webkit)[ \/]([\w.]+)/, - ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, - rmsie = /(msie) ([\w.]+)/, - rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, - - // Matches dashed string for camelizing - rdashAlpha = /-([a-z]|[0-9])/ig, - rmsPrefix = /^-ms-/, - - // Used by jQuery.camelCase as callback to replace() - fcamelCase = function( all, letter ) { - return ( letter + "" ).toUpperCase(); - }, - - // Keep a UserAgent string for use with jQuery.browser - userAgent = navigator.userAgent, - - // For matching the engine and version of the browser - browserMatch, - - // The deferred used on DOM ready - readyList, - - // The ready event handler - DOMContentLoaded, - - // Save a reference to some core methods - toString = Object.prototype.toString, - hasOwn = Object.prototype.hasOwnProperty, - push = Array.prototype.push, - slice = Array.prototype.slice, - trim = String.prototype.trim, - indexOf = Array.prototype.indexOf, - - // [[Class]] -> type pairs - class2type = {}; - -jQuery.fn = jQuery.prototype = { - constructor: jQuery, - init: function( selector, context, rootjQuery ) { - var match, elem, ret, doc; - - // Handle $(""), $(null), or $(undefined) - if ( !selector ) { - return this; - } - - // Handle $(DOMElement) - if ( selector.nodeType ) { - this.context = this[0] = selector; - this.length = 1; - return this; - } - - // The body element only exists once, optimize finding it - if ( selector === "body" && !context && document.body ) { - this.context = document; - this[0] = document.body; - this.selector = selector; - this.length = 1; - return this; - } - - // Handle HTML strings - if ( typeof selector === "string" ) { - // Are we dealing with HTML string or an ID? - if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { - // Assume that strings that start and end with <> are HTML and skip the regex check - match = [ null, selector, null ]; - - } else { - match = quickExpr.exec( selector ); - } - - // Verify a match, and that no context was specified for #id - if ( match && (match[1] || !context) ) { - - // HANDLE: $(html) -> $(array) - if ( match[1] ) { - context = context instanceof jQuery ? context[0] : context; - doc = ( context ? context.ownerDocument || context : document ); - - // If a single string is passed in and it's a single tag - // just do a createElement and skip the rest - ret = rsingleTag.exec( selector ); - - if ( ret ) { - if ( jQuery.isPlainObject( context ) ) { - selector = [ document.createElement( ret[1] ) ]; - jQuery.fn.attr.call( selector, context, true ); - - } else { - selector = [ doc.createElement( ret[1] ) ]; - } - - } else { - ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); - selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes; - } - - return jQuery.merge( this, selector ); - - // HANDLE: $("#id") - } else { - elem = document.getElementById( match[2] ); - - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - if ( elem && elem.parentNode ) { - // Handle the case where IE and Opera return items - // by name instead of ID - if ( elem.id !== match[2] ) { - return rootjQuery.find( selector ); - } - - // Otherwise, we inject the element directly into the jQuery object - this.length = 1; - this[0] = elem; - } - - this.context = document; - this.selector = selector; - return this; - } - - // HANDLE: $(expr, $(...)) - } else if ( !context || context.jquery ) { - return ( context || rootjQuery ).find( selector ); - - // HANDLE: $(expr, context) - // (which is just equivalent to: $(context).find(expr) - } else { - return this.constructor( context ).find( selector ); - } - - // HANDLE: $(function) - // Shortcut for document ready - } else if ( jQuery.isFunction( selector ) ) { - return rootjQuery.ready( selector ); - } - - if ( selector.selector !== undefined ) { - this.selector = selector.selector; - this.context = selector.context; - } - - return jQuery.makeArray( selector, this ); - }, - - // Start with an empty selector - selector: "", - - // The current version of jQuery being used - jquery: "1.7.2", - - // The default length of a jQuery object is 0 - length: 0, - - // The number of elements contained in the matched element set - size: function() { - return this.length; - }, - - toArray: function() { - return slice.call( this, 0 ); - }, - - // Get the Nth element in the matched element set OR - // Get the whole matched element set as a clean array - get: function( num ) { - return num == null ? - - // Return a 'clean' array - this.toArray() : - - // Return just the object - ( num < 0 ? this[ this.length + num ] : this[ num ] ); - }, - - // Take an array of elements and push it onto the stack - // (returning the new matched element set) - pushStack: function( elems, name, selector ) { - // Build a new jQuery matched element set - var ret = this.constructor(); - - if ( jQuery.isArray( elems ) ) { - push.apply( ret, elems ); - - } else { - jQuery.merge( ret, elems ); - } - - // Add the old object onto the stack (as a reference) - ret.prevObject = this; - - ret.context = this.context; - - if ( name === "find" ) { - ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; - } else if ( name ) { - ret.selector = this.selector + "." + name + "(" + selector + ")"; - } - - // Return the newly-formed element set - return ret; - }, - - // Execute a callback for every element in the matched set. - // (You can seed the arguments with an array of args, but this is - // only used internally.) - each: function( callback, args ) { - return jQuery.each( this, callback, args ); - }, - - ready: function( fn ) { - // Attach the listeners - jQuery.bindReady(); - - // Add the callback - readyList.add( fn ); - - return this; - }, - - eq: function( i ) { - i = +i; - return i === -1 ? - this.slice( i ) : - this.slice( i, i + 1 ); - }, - - first: function() { - return this.eq( 0 ); - }, - - last: function() { - return this.eq( -1 ); - }, - - slice: function() { - return this.pushStack( slice.apply( this, arguments ), - "slice", slice.call(arguments).join(",") ); - }, - - map: function( callback ) { - return this.pushStack( jQuery.map(this, function( elem, i ) { - return callback.call( elem, i, elem ); - })); - }, - - end: function() { - return this.prevObject || this.constructor(null); - }, - - // For internal use only. - // Behaves like an Array's method, not like a jQuery method. - push: push, - sort: [].sort, - splice: [].splice -}; - -// Give the init function the jQuery prototype for later instantiation -jQuery.fn.init.prototype = jQuery.fn; - -jQuery.extend = jQuery.fn.extend = function() { - var options, name, src, copy, copyIsArray, clone, - target = arguments[0] || {}, - i = 1, - length = arguments.length, - deep = false; - - // Handle a deep copy situation - if ( typeof target === "boolean" ) { - deep = target; - target = arguments[1] || {}; - // skip the boolean and the target - i = 2; - } - - // Handle case when target is a string or something (possible in deep copy) - if ( typeof target !== "object" && !jQuery.isFunction(target) ) { - target = {}; - } - - // extend jQuery itself if only one argument is passed - if ( length === i ) { - target = this; - --i; - } - - for ( ; i < length; i++ ) { - // Only deal with non-null/undefined values - if ( (options = arguments[ i ]) != null ) { - // Extend the base object - for ( name in options ) { - src = target[ name ]; - copy = options[ name ]; - - // Prevent never-ending loop - if ( target === copy ) { - continue; - } - - // Recurse if we're merging plain objects or arrays - if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { - if ( copyIsArray ) { - copyIsArray = false; - clone = src && jQuery.isArray(src) ? src : []; - - } else { - clone = src && jQuery.isPlainObject(src) ? src : {}; - } - - // Never move original objects, clone them - target[ name ] = jQuery.extend( deep, clone, copy ); - - // Don't bring in undefined values - } else if ( copy !== undefined ) { - target[ name ] = copy; - } - } - } - } - - // Return the modified object - return target; -}; - -jQuery.extend({ - noConflict: function( deep ) { - if ( window.$ === jQuery ) { - window.$ = _$; - } - - if ( deep && window.jQuery === jQuery ) { - window.jQuery = _jQuery; - } - - return jQuery; - }, - - // Is the DOM ready to be used? Set to true once it occurs. - isReady: false, - - // A counter to track how many items to wait for before - // the ready event fires. See #6781 - readyWait: 1, - - // Hold (or release) the ready event - holdReady: function( hold ) { - if ( hold ) { - jQuery.readyWait++; - } else { - jQuery.ready( true ); - } - }, - - // Handle when the DOM is ready - ready: function( wait ) { - // Either a released hold or an DOMready/load event and not yet ready - if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) { - // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). - if ( !document.body ) { - return setTimeout( jQuery.ready, 1 ); - } - - // Remember that the DOM is ready - jQuery.isReady = true; - - // If a normal DOM Ready event fired, decrement, and wait if need be - if ( wait !== true && --jQuery.readyWait > 0 ) { - return; - } - - // If there are functions bound, to execute - readyList.fireWith( document, [ jQuery ] ); - - // Trigger any bound ready events - if ( jQuery.fn.trigger ) { - jQuery( document ).trigger( "ready" ).off( "ready" ); - } - } - }, - - bindReady: function() { - if ( readyList ) { - return; - } - - readyList = jQuery.Callbacks( "once memory" ); - - // Catch cases where $(document).ready() is called after the - // browser event has already occurred. - if ( document.readyState === "complete" ) { - // Handle it asynchronously to allow scripts the opportunity to delay ready - return setTimeout( jQuery.ready, 1 ); - } - - // Mozilla, Opera and webkit nightlies currently support this event - if ( document.addEventListener ) { - // Use the handy event callback - document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); - - // A fallback to window.onload, that will always work - window.addEventListener( "load", jQuery.ready, false ); - - // If IE event model is used - } else if ( document.attachEvent ) { - // ensure firing before onload, - // maybe late but safe also for iframes - document.attachEvent( "onreadystatechange", DOMContentLoaded ); - - // A fallback to window.onload, that will always work - window.attachEvent( "onload", jQuery.ready ); - - // If IE and not a frame - // continually check to see if the document is ready - var toplevel = false; - - try { - toplevel = window.frameElement == null; - } catch(e) {} - - if ( document.documentElement.doScroll && toplevel ) { - doScrollCheck(); - } - } - }, - - // See test/unit/core.js for details concerning isFunction. - // Since version 1.3, DOM methods and functions like alert - // aren't supported. They return false on IE (#2968). - isFunction: function( obj ) { - return jQuery.type(obj) === "function"; - }, - - isArray: Array.isArray || function( obj ) { - return jQuery.type(obj) === "array"; - }, - - isWindow: function( obj ) { - return obj != null && obj == obj.window; - }, - - isNumeric: function( obj ) { - return !isNaN( parseFloat(obj) ) && isFinite( obj ); - }, - - type: function( obj ) { - return obj == null ? - String( obj ) : - class2type[ toString.call(obj) ] || "object"; - }, - - isPlainObject: function( obj ) { - // Must be an Object. - // Because of IE, we also have to check the presence of the constructor property. - // Make sure that DOM nodes and window objects don't pass through, as well - if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { - return false; - } - - try { - // Not own constructor property must be Object - if ( obj.constructor && - !hasOwn.call(obj, "constructor") && - !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { - return false; - } - } catch ( e ) { - // IE8,9 Will throw exceptions on certain host objects #9897 - return false; - } - - // Own properties are enumerated firstly, so to speed up, - // if last one is own, then all properties are own. - - var key; - for ( key in obj ) {} - - return key === undefined || hasOwn.call( obj, key ); - }, - - isEmptyObject: function( obj ) { - for ( var name in obj ) { - return false; - } - return true; - }, - - error: function( msg ) { - throw new Error( msg ); - }, - - parseJSON: function( data ) { - if ( typeof data !== "string" || !data ) { - return null; - } - - // Make sure leading/trailing whitespace is removed (IE can't handle it) - data = jQuery.trim( data ); - - // Attempt to parse using the native JSON parser first - if ( window.JSON && window.JSON.parse ) { - return window.JSON.parse( data ); - } - - // Make sure the incoming data is actual JSON - // Logic borrowed from http://json.org/json2.js - if ( rvalidchars.test( data.replace( rvalidescape, "@" ) - .replace( rvalidtokens, "]" ) - .replace( rvalidbraces, "")) ) { - - return ( new Function( "return " + data ) )(); - - } - jQuery.error( "Invalid JSON: " + data ); - }, - - // Cross-browser xml parsing - parseXML: function( data ) { - if ( typeof data !== "string" || !data ) { - return null; - } - var xml, tmp; - try { - if ( window.DOMParser ) { // Standard - tmp = new DOMParser(); - xml = tmp.parseFromString( data , "text/xml" ); - } else { // IE - xml = new ActiveXObject( "Microsoft.XMLDOM" ); - xml.async = "false"; - xml.loadXML( data ); - } - } catch( e ) { - xml = undefined; - } - if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { - jQuery.error( "Invalid XML: " + data ); - } - return xml; - }, - - noop: function() {}, - - // Evaluates a script in a global context - // Workarounds based on findings by Jim Driscoll - // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context - globalEval: function( data ) { - if ( data && rnotwhite.test( data ) ) { - // We use execScript on Internet Explorer - // We use an anonymous function so that context is window - // rather than jQuery in Firefox - ( window.execScript || function( data ) { - window[ "eval" ].call( window, data ); - } )( data ); - } - }, - - // Convert dashed to camelCase; used by the css and data modules - // Microsoft forgot to hump their vendor prefix (#9572) - camelCase: function( string ) { - return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); - }, - - nodeName: function( elem, name ) { - return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); - }, - - // args is for internal usage only - each: function( object, callback, args ) { - var name, i = 0, - length = object.length, - isObj = length === undefined || jQuery.isFunction( object ); - - if ( args ) { - if ( isObj ) { - for ( name in object ) { - if ( callback.apply( object[ name ], args ) === false ) { - break; - } - } - } else { - for ( ; i < length; ) { - if ( callback.apply( object[ i++ ], args ) === false ) { - break; - } - } - } - - // A special, fast, case for the most common use of each - } else { - if ( isObj ) { - for ( name in object ) { - if ( callback.call( object[ name ], name, object[ name ] ) === false ) { - break; - } - } - } else { - for ( ; i < length; ) { - if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) { - break; - } - } - } - } - - return object; - }, - - // Use native String.trim function wherever possible - trim: trim ? - function( text ) { - return text == null ? - "" : - trim.call( text ); - } : - - // Otherwise use our own trimming functionality - function( text ) { - return text == null ? - "" : - text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); - }, - - // results is for internal usage only - makeArray: function( array, results ) { - var ret = results || []; - - if ( array != null ) { - // The window, strings (and functions) also have 'length' - // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 - var type = jQuery.type( array ); - - if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { - push.call( ret, array ); - } else { - jQuery.merge( ret, array ); - } - } - - return ret; - }, - - inArray: function( elem, array, i ) { - var len; - - if ( array ) { - if ( indexOf ) { - return indexOf.call( array, elem, i ); - } - - len = array.length; - i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; - - for ( ; i < len; i++ ) { - // Skip accessing in sparse arrays - if ( i in array && array[ i ] === elem ) { - return i; - } - } - } - - return -1; - }, - - merge: function( first, second ) { - var i = first.length, - j = 0; - - if ( typeof second.length === "number" ) { - for ( var l = second.length; j < l; j++ ) { - first[ i++ ] = second[ j ]; - } - - } else { - while ( second[j] !== undefined ) { - first[ i++ ] = second[ j++ ]; - } - } - - first.length = i; - - return first; - }, - - grep: function( elems, callback, inv ) { - var ret = [], retVal; - inv = !!inv; - - // Go through the array, only saving the items - // that pass the validator function - for ( var i = 0, length = elems.length; i < length; i++ ) { - retVal = !!callback( elems[ i ], i ); - if ( inv !== retVal ) { - ret.push( elems[ i ] ); - } - } - - return ret; - }, - - // arg is for internal usage only - map: function( elems, callback, arg ) { - var value, key, ret = [], - i = 0, - length = elems.length, - // jquery objects are treated as arrays - isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; - - // Go through the array, translating each of the items to their - if ( isArray ) { - for ( ; i < length; i++ ) { - value = callback( elems[ i ], i, arg ); - - if ( value != null ) { - ret[ ret.length ] = value; - } - } - - // Go through every key on the object, - } else { - for ( key in elems ) { - value = callback( elems[ key ], key, arg ); - - if ( value != null ) { - ret[ ret.length ] = value; - } - } - } - - // Flatten any nested arrays - return ret.concat.apply( [], ret ); - }, - - // A global GUID counter for objects - guid: 1, - - // Bind a function to a context, optionally partially applying any - // arguments. - proxy: function( fn, context ) { - if ( typeof context === "string" ) { - var tmp = fn[ context ]; - context = fn; - fn = tmp; - } - - // Quick check to determine if target is callable, in the spec - // this throws a TypeError, but we will just return undefined. - if ( !jQuery.isFunction( fn ) ) { - return undefined; - } - - // Simulated bind - var args = slice.call( arguments, 2 ), - proxy = function() { - return fn.apply( context, args.concat( slice.call( arguments ) ) ); - }; - - // Set the guid of unique handler to the same of original handler, so it can be removed - proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; - - return proxy; - }, - - // Mutifunctional method to get and set values to a collection - // The value/s can optionally be executed if it's a function - access: function( elems, fn, key, value, chainable, emptyGet, pass ) { - var exec, - bulk = key == null, - i = 0, - length = elems.length; - - // Sets many values - if ( key && typeof key === "object" ) { - for ( i in key ) { - jQuery.access( elems, fn, i, key[i], 1, emptyGet, value ); - } - chainable = 1; - - // Sets one value - } else if ( value !== undefined ) { - // Optionally, function values get executed if exec is true - exec = pass === undefined && jQuery.isFunction( value ); - - if ( bulk ) { - // Bulk operations only iterate when executing function values - if ( exec ) { - exec = fn; - fn = function( elem, key, value ) { - return exec.call( jQuery( elem ), value ); - }; - - // Otherwise they run against the entire set - } else { - fn.call( elems, value ); - fn = null; - } - } - - if ( fn ) { - for (; i < length; i++ ) { - fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); - } - } - - chainable = 1; - } - - return chainable ? - elems : - - // Gets - bulk ? - fn.call( elems ) : - length ? fn( elems[0], key ) : emptyGet; - }, - - now: function() { - return ( new Date() ).getTime(); - }, - - // Use of jQuery.browser is frowned upon. - // More details: http://docs.jquery.com/Utilities/jQuery.browser - uaMatch: function( ua ) { - ua = ua.toLowerCase(); - - var match = rwebkit.exec( ua ) || - ropera.exec( ua ) || - rmsie.exec( ua ) || - ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || - []; - - return { browser: match[1] || "", version: match[2] || "0" }; - }, - - sub: function() { - function jQuerySub( selector, context ) { - return new jQuerySub.fn.init( selector, context ); - } - jQuery.extend( true, jQuerySub, this ); - jQuerySub.superclass = this; - jQuerySub.fn = jQuerySub.prototype = this(); - jQuerySub.fn.constructor = jQuerySub; - jQuerySub.sub = this.sub; - jQuerySub.fn.init = function init( selector, context ) { - if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { - context = jQuerySub( context ); - } - - return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); - }; - jQuerySub.fn.init.prototype = jQuerySub.fn; - var rootjQuerySub = jQuerySub(document); - return jQuerySub; - }, - - browser: {} -}); - -// Populate the class2type map -jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { - class2type[ "[object " + name + "]" ] = name.toLowerCase(); -}); - -browserMatch = jQuery.uaMatch( userAgent ); -if ( browserMatch.browser ) { - jQuery.browser[ browserMatch.browser ] = true; - jQuery.browser.version = browserMatch.version; -} - -// Deprecated, use jQuery.browser.webkit instead -if ( jQuery.browser.webkit ) { - jQuery.browser.safari = true; -} - -// IE doesn't match non-breaking spaces with \s -if ( rnotwhite.test( "\xA0" ) ) { - trimLeft = /^[\s\xA0]+/; - trimRight = /[\s\xA0]+$/; -} - -// All jQuery objects should point back to these -rootjQuery = jQuery(document); - -// Cleanup functions for the document ready method -if ( document.addEventListener ) { - DOMContentLoaded = function() { - document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); - jQuery.ready(); - }; - -} else if ( document.attachEvent ) { - DOMContentLoaded = function() { - // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). - if ( document.readyState === "complete" ) { - document.detachEvent( "onreadystatechange", DOMContentLoaded ); - jQuery.ready(); - } - }; -} - -// The DOM ready check for Internet Explorer -function doScrollCheck() { - if ( jQuery.isReady ) { - return; - } - - try { - // If IE is used, use the trick by Diego Perini - // http://javascript.nwbox.com/IEContentLoaded/ - document.documentElement.doScroll("left"); - } catch(e) { - setTimeout( doScrollCheck, 1 ); - return; - } - - // and execute any waiting functions - jQuery.ready(); -} - -return jQuery; - -})(); - - -// String to Object flags format cache -var flagsCache = {}; - -// Convert String-formatted flags into Object-formatted ones and store in cache -function createFlags( flags ) { - var object = flagsCache[ flags ] = {}, - i, length; - flags = flags.split( /\s+/ ); - for ( i = 0, length = flags.length; i < length; i++ ) { - object[ flags[i] ] = true; - } - return object; -} - -/* - * Create a callback list using the following parameters: - * - * flags: an optional list of space-separated flags that will change how - * the callback list behaves - * - * By default a callback list will act like an event callback list and can be - * "fired" multiple times. - * - * Possible flags: - * - * once: will ensure the callback list can only be fired once (like a Deferred) - * - * memory: will keep track of previous values and will call any callback added - * after the list has been fired right away with the latest "memorized" - * values (like a Deferred) - * - * unique: will ensure a callback can only be added once (no duplicate in the list) - * - * stopOnFalse: interrupt callings when a callback returns false - * - */ -jQuery.Callbacks = function( flags ) { - - // Convert flags from String-formatted to Object-formatted - // (we check in cache first) - flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {}; - - var // Actual callback list - list = [], - // Stack of fire calls for repeatable lists - stack = [], - // Last fire value (for non-forgettable lists) - memory, - // Flag to know if list was already fired - fired, - // Flag to know if list is currently firing - firing, - // First callback to fire (used internally by add and fireWith) - firingStart, - // End of the loop when firing - firingLength, - // Index of currently firing callback (modified by remove if needed) - firingIndex, - // Add one or several callbacks to the list - add = function( args ) { - var i, - length, - elem, - type, - actual; - for ( i = 0, length = args.length; i < length; i++ ) { - elem = args[ i ]; - type = jQuery.type( elem ); - if ( type === "array" ) { - // Inspect recursively - add( elem ); - } else if ( type === "function" ) { - // Add if not in unique mode and callback is not in - if ( !flags.unique || !self.has( elem ) ) { - list.push( elem ); - } - } - } - }, - // Fire callbacks - fire = function( context, args ) { - args = args || []; - memory = !flags.memory || [ context, args ]; - fired = true; - firing = true; - firingIndex = firingStart || 0; - firingStart = 0; - firingLength = list.length; - for ( ; list && firingIndex < firingLength; firingIndex++ ) { - if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) { - memory = true; // Mark as halted - break; - } - } - firing = false; - if ( list ) { - if ( !flags.once ) { - if ( stack && stack.length ) { - memory = stack.shift(); - self.fireWith( memory[ 0 ], memory[ 1 ] ); - } - } else if ( memory === true ) { - self.disable(); - } else { - list = []; - } - } - }, - // Actual Callbacks object - self = { - // Add a callback or a collection of callbacks to the list - add: function() { - if ( list ) { - var length = list.length; - add( arguments ); - // Do we need to add the callbacks to the - // current firing batch? - if ( firing ) { - firingLength = list.length; - // With memory, if we're not firing then - // we should call right away, unless previous - // firing was halted (stopOnFalse) - } else if ( memory && memory !== true ) { - firingStart = length; - fire( memory[ 0 ], memory[ 1 ] ); - } - } - return this; - }, - // Remove a callback from the list - remove: function() { - if ( list ) { - var args = arguments, - argIndex = 0, - argLength = args.length; - for ( ; argIndex < argLength ; argIndex++ ) { - for ( var i = 0; i < list.length; i++ ) { - if ( args[ argIndex ] === list[ i ] ) { - // Handle firingIndex and firingLength - if ( firing ) { - if ( i <= firingLength ) { - firingLength--; - if ( i <= firingIndex ) { - firingIndex--; - } - } - } - // Remove the element - list.splice( i--, 1 ); - // If we have some unicity property then - // we only need to do this once - if ( flags.unique ) { - break; - } - } - } - } - } - return this; - }, - // Control if a given callback is in the list - has: function( fn ) { - if ( list ) { - var i = 0, - length = list.length; - for ( ; i < length; i++ ) { - if ( fn === list[ i ] ) { - return true; - } - } - } - return false; - }, - // Remove all callbacks from the list - empty: function() { - list = []; - return this; - }, - // Have the list do nothing anymore - disable: function() { - list = stack = memory = undefined; - return this; - }, - // Is it disabled? - disabled: function() { - return !list; - }, - // Lock the list in its current state - lock: function() { - stack = undefined; - if ( !memory || memory === true ) { - self.disable(); - } - return this; - }, - // Is it locked? - locked: function() { - return !stack; - }, - // Call all callbacks with the given context and arguments - fireWith: function( context, args ) { - if ( stack ) { - if ( firing ) { - if ( !flags.once ) { - stack.push( [ context, args ] ); - } - } else if ( !( flags.once && memory ) ) { - fire( context, args ); - } - } - return this; - }, - // Call all the callbacks with the given arguments - fire: function() { - self.fireWith( this, arguments ); - return this; - }, - // To know if the callbacks have already been called at least once - fired: function() { - return !!fired; - } - }; - - return self; -}; - - - - -var // Static reference to slice - sliceDeferred = [].slice; - -jQuery.extend({ - - Deferred: function( func ) { - var doneList = jQuery.Callbacks( "once memory" ), - failList = jQuery.Callbacks( "once memory" ), - progressList = jQuery.Callbacks( "memory" ), - state = "pending", - lists = { - resolve: doneList, - reject: failList, - notify: progressList - }, - promise = { - done: doneList.add, - fail: failList.add, - progress: progressList.add, - - state: function() { - return state; - }, - - // Deprecated - isResolved: doneList.fired, - isRejected: failList.fired, - - then: function( doneCallbacks, failCallbacks, progressCallbacks ) { - deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks ); - return this; - }, - always: function() { - deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments ); - return this; - }, - pipe: function( fnDone, fnFail, fnProgress ) { - return jQuery.Deferred(function( newDefer ) { - jQuery.each( { - done: [ fnDone, "resolve" ], - fail: [ fnFail, "reject" ], - progress: [ fnProgress, "notify" ] - }, function( handler, data ) { - var fn = data[ 0 ], - action = data[ 1 ], - returned; - if ( jQuery.isFunction( fn ) ) { - deferred[ handler ](function() { - returned = fn.apply( this, arguments ); - if ( returned && jQuery.isFunction( returned.promise ) ) { - returned.promise().then( newDefer.resolve, newDefer.reject, newDefer.notify ); - } else { - newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); - } - }); - } else { - deferred[ handler ]( newDefer[ action ] ); - } - }); - }).promise(); - }, - // Get a promise for this deferred - // If obj is provided, the promise aspect is added to the object - promise: function( obj ) { - if ( obj == null ) { - obj = promise; - } else { - for ( var key in promise ) { - obj[ key ] = promise[ key ]; - } - } - return obj; - } - }, - deferred = promise.promise({}), - key; - - for ( key in lists ) { - deferred[ key ] = lists[ key ].fire; - deferred[ key + "With" ] = lists[ key ].fireWith; - } - - // Handle state - deferred.done( function() { - state = "resolved"; - }, failList.disable, progressList.lock ).fail( function() { - state = "rejected"; - }, doneList.disable, progressList.lock ); - - // Call given func if any - if ( func ) { - func.call( deferred, deferred ); - } - - // All done! - return deferred; - }, - - // Deferred helper - when: function( firstParam ) { - var args = sliceDeferred.call( arguments, 0 ), - i = 0, - length = args.length, - pValues = new Array( length ), - count = length, - pCount = length, - deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? - firstParam : - jQuery.Deferred(), - promise = deferred.promise(); - function resolveFunc( i ) { - return function( value ) { - args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; - if ( !( --count ) ) { - deferred.resolveWith( deferred, args ); - } - }; - } - function progressFunc( i ) { - return function( value ) { - pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; - deferred.notifyWith( promise, pValues ); - }; - } - if ( length > 1 ) { - for ( ; i < length; i++ ) { - if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) { - args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) ); - } else { - --count; - } - } - if ( !count ) { - deferred.resolveWith( deferred, args ); - } - } else if ( deferred !== firstParam ) { - deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); - } - return promise; - } -}); - - - - -jQuery.support = (function() { - - var support, - all, - a, - select, - opt, - input, - fragment, - tds, - events, - eventName, - i, - isSupported, - div = document.createElement( "div" ), - documentElement = document.documentElement; - - // Preliminary tests - div.setAttribute("className", "t"); - div.innerHTML = "
a"; - - all = div.getElementsByTagName( "*" ); - a = div.getElementsByTagName( "a" )[ 0 ]; - - // Can't get basic test support - if ( !all || !all.length || !a ) { - return {}; - } - - // First batch of supports tests - select = document.createElement( "select" ); - opt = select.appendChild( document.createElement("option") ); - input = div.getElementsByTagName( "input" )[ 0 ]; - - support = { - // IE strips leading whitespace when .innerHTML is used - leadingWhitespace: ( div.firstChild.nodeType === 3 ), - - // Make sure that tbody elements aren't automatically inserted - // IE will insert them into empty tables - tbody: !div.getElementsByTagName("tbody").length, - - // Make sure that link elements get serialized correctly by innerHTML - // This requires a wrapper element in IE - htmlSerialize: !!div.getElementsByTagName("link").length, - - // Get the style information from getAttribute - // (IE uses .cssText instead) - style: /top/.test( a.getAttribute("style") ), - - // Make sure that URLs aren't manipulated - // (IE normalizes it by default) - hrefNormalized: ( a.getAttribute("href") === "/a" ), - - // Make sure that element opacity exists - // (IE uses filter instead) - // Use a regex to work around a WebKit issue. See #5145 - opacity: /^0.55/.test( a.style.opacity ), - - // Verify style float existence - // (IE uses styleFloat instead of cssFloat) - cssFloat: !!a.style.cssFloat, - - // Make sure that if no value is specified for a checkbox - // that it defaults to "on". - // (WebKit defaults to "" instead) - checkOn: ( input.value === "on" ), - - // Make sure that a selected-by-default option has a working selected property. - // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) - optSelected: opt.selected, - - // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) - getSetAttribute: div.className !== "t", - - // Tests for enctype support on a form(#6743) - enctype: !!document.createElement("form").enctype, - - // Makes sure cloning an html5 element does not cause problems - // Where outerHTML is undefined, this still works - html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav>", - - // Will be defined later - submitBubbles: true, - changeBubbles: true, - focusinBubbles: false, - deleteExpando: true, - noCloneEvent: true, - inlineBlockNeedsLayout: false, - shrinkWrapBlocks: false, - reliableMarginRight: true, - pixelMargin: true - }; - - // jQuery.boxModel DEPRECATED in 1.3, use jQuery.support.boxModel instead - jQuery.boxModel = support.boxModel = (document.compatMode === "CSS1Compat"); - - // Make sure checked status is properly cloned - input.checked = true; - support.noCloneChecked = input.cloneNode( true ).checked; - - // Make sure that the options inside disabled selects aren't marked as disabled - // (WebKit marks them as disabled) - select.disabled = true; - support.optDisabled = !opt.disabled; - - // Test to see if it's possible to delete an expando from an element - // Fails in Internet Explorer - try { - delete div.test; - } catch( e ) { - support.deleteExpando = false; - } - - if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { - div.attachEvent( "onclick", function() { - // Cloning a node shouldn't copy over any - // bound event handlers (IE does this) - support.noCloneEvent = false; - }); - div.cloneNode( true ).fireEvent( "onclick" ); - } - - // Check if a radio maintains its value - // after being appended to the DOM - input = document.createElement("input"); - input.value = "t"; - input.setAttribute("type", "radio"); - support.radioValue = input.value === "t"; - - input.setAttribute("checked", "checked"); - - // #11217 - WebKit loses check when the name is after the checked attribute - input.setAttribute( "name", "t" ); - - div.appendChild( input ); - fragment = document.createDocumentFragment(); - fragment.appendChild( div.lastChild ); - - // WebKit doesn't clone checked state correctly in fragments - support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; - - // Check if a disconnected checkbox will retain its checked - // value of true after appended to the DOM (IE6/7) - support.appendChecked = input.checked; - - fragment.removeChild( input ); - fragment.appendChild( div ); - - // Technique from Juriy Zaytsev - // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ - // We only care about the case where non-standard event systems - // are used, namely in IE. Short-circuiting here helps us to - // avoid an eval call (in setAttribute) which can cause CSP - // to go haywire. See: https://developer.mozilla.org/en/Security/CSP - if ( div.attachEvent ) { - for ( i in { - submit: 1, - change: 1, - focusin: 1 - }) { - eventName = "on" + i; - isSupported = ( eventName in div ); - if ( !isSupported ) { - div.setAttribute( eventName, "return;" ); - isSupported = ( typeof div[ eventName ] === "function" ); - } - support[ i + "Bubbles" ] = isSupported; - } - } - - fragment.removeChild( div ); - - // Null elements to avoid leaks in IE - fragment = select = opt = div = input = null; - - // Run tests that need a body at doc ready - jQuery(function() { - var container, outer, inner, table, td, offsetSupport, - marginDiv, conMarginTop, style, html, positionTopLeftWidthHeight, - paddingMarginBorderVisibility, paddingMarginBorder, - body = document.getElementsByTagName("body")[0]; - - if ( !body ) { - // Return for frameset docs that don't have a body - return; - } - - conMarginTop = 1; - paddingMarginBorder = "padding:0;margin:0;border:"; - positionTopLeftWidthHeight = "position:absolute;top:0;left:0;width:1px;height:1px;"; - paddingMarginBorderVisibility = paddingMarginBorder + "0;visibility:hidden;"; - style = "style='" + positionTopLeftWidthHeight + paddingMarginBorder + "5px solid #000;"; - html = "
" + - "" + - "
"; - - container = document.createElement("div"); - container.style.cssText = paddingMarginBorderVisibility + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px"; - body.insertBefore( container, body.firstChild ); - - // Construct the test element - div = document.createElement("div"); - container.appendChild( div ); - - // Check if table cells still have offsetWidth/Height when they are set - // to display:none and there are still other visible table cells in a - // table row; if so, offsetWidth/Height are not reliable for use when - // determining if an element has been hidden directly using - // display:none (it is still safe to use offsets if a parent element is - // hidden; don safety goggles and see bug #4512 for more information). - // (only IE 8 fails this test) - div.innerHTML = "
t
"; - tds = div.getElementsByTagName( "td" ); - isSupported = ( tds[ 0 ].offsetHeight === 0 ); - - tds[ 0 ].style.display = ""; - tds[ 1 ].style.display = "none"; - - // Check if empty table cells still have offsetWidth/Height - // (IE <= 8 fail this test) - support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); - - // Check if div with explicit width and no margin-right incorrectly - // gets computed margin-right based on width of container. For more - // info see bug #3333 - // Fails in WebKit before Feb 2011 nightlies - // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right - if ( window.getComputedStyle ) { - div.innerHTML = ""; - marginDiv = document.createElement( "div" ); - marginDiv.style.width = "0"; - marginDiv.style.marginRight = "0"; - div.style.width = "2px"; - div.appendChild( marginDiv ); - support.reliableMarginRight = - ( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0; - } - - if ( typeof div.style.zoom !== "undefined" ) { - // Check if natively block-level elements act like inline-block - // elements when setting their display to 'inline' and giving - // them layout - // (IE < 8 does this) - div.innerHTML = ""; - div.style.width = div.style.padding = "1px"; - div.style.border = 0; - div.style.overflow = "hidden"; - div.style.display = "inline"; - div.style.zoom = 1; - support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); - - // Check if elements with layout shrink-wrap their children - // (IE 6 does this) - div.style.display = "block"; - div.style.overflow = "visible"; - div.innerHTML = "
"; - support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); - } - - div.style.cssText = positionTopLeftWidthHeight + paddingMarginBorderVisibility; - div.innerHTML = html; - - outer = div.firstChild; - inner = outer.firstChild; - td = outer.nextSibling.firstChild.firstChild; - - offsetSupport = { - doesNotAddBorder: ( inner.offsetTop !== 5 ), - doesAddBorderForTableAndCells: ( td.offsetTop === 5 ) - }; - - inner.style.position = "fixed"; - inner.style.top = "20px"; - - // safari subtracts parent border width here which is 5px - offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 ); - inner.style.position = inner.style.top = ""; - - outer.style.overflow = "hidden"; - outer.style.position = "relative"; - - offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 ); - offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop ); - - if ( window.getComputedStyle ) { - div.style.marginTop = "1%"; - support.pixelMargin = ( window.getComputedStyle( div, null ) || { marginTop: 0 } ).marginTop !== "1%"; - } - - if ( typeof container.style.zoom !== "undefined" ) { - container.style.zoom = 1; - } - - body.removeChild( container ); - marginDiv = div = container = null; - - jQuery.extend( support, offsetSupport ); - }); - - return support; -})(); - - - - -var rbrace = /^(?:\{.*\}|\[.*\])$/, - rmultiDash = /([A-Z])/g; - -jQuery.extend({ - cache: {}, - - // Please use with caution - uuid: 0, - - // Unique for each copy of jQuery on the page - // Non-digits removed to match rinlinejQuery - expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), - - // The following elements throw uncatchable exceptions if you - // attempt to add expando properties to them. - noData: { - "embed": true, - // Ban all objects except for Flash (which handle expandos) - "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", - "applet": true - }, - - hasData: function( elem ) { - elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; - return !!elem && !isEmptyDataObject( elem ); - }, - - data: function( elem, name, data, pvt /* Internal Use Only */ ) { - if ( !jQuery.acceptData( elem ) ) { - return; - } - - var privateCache, thisCache, ret, - internalKey = jQuery.expando, - getByName = typeof name === "string", - - // We have to handle DOM nodes and JS objects differently because IE6-7 - // can't GC object references properly across the DOM-JS boundary - isNode = elem.nodeType, - - // Only DOM nodes need the global jQuery cache; JS object data is - // attached directly to the object so GC can occur automatically - cache = isNode ? jQuery.cache : elem, - - // Only defining an ID for JS objects if its cache already exists allows - // the code to shortcut on the same path as a DOM node with no cache - id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey, - isEvents = name === "events"; - - // Avoid doing any more work than we need to when trying to get data on an - // object that has no data at all - if ( (!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) { - return; - } - - if ( !id ) { - // Only DOM nodes need a new unique ID for each element since their data - // ends up in the global cache - if ( isNode ) { - elem[ internalKey ] = id = ++jQuery.uuid; - } else { - id = internalKey; - } - } - - if ( !cache[ id ] ) { - cache[ id ] = {}; - - // Avoids exposing jQuery metadata on plain JS objects when the object - // is serialized using JSON.stringify - if ( !isNode ) { - cache[ id ].toJSON = jQuery.noop; - } - } - - // An object can be passed to jQuery.data instead of a key/value pair; this gets - // shallow copied over onto the existing cache - if ( typeof name === "object" || typeof name === "function" ) { - if ( pvt ) { - cache[ id ] = jQuery.extend( cache[ id ], name ); - } else { - cache[ id ].data = jQuery.extend( cache[ id ].data, name ); - } - } - - privateCache = thisCache = cache[ id ]; - - // jQuery data() is stored in a separate object inside the object's internal data - // cache in order to avoid key collisions between internal data and user-defined - // data. - if ( !pvt ) { - if ( !thisCache.data ) { - thisCache.data = {}; - } - - thisCache = thisCache.data; - } - - if ( data !== undefined ) { - thisCache[ jQuery.camelCase( name ) ] = data; - } - - // Users should not attempt to inspect the internal events object using jQuery.data, - // it is undocumented and subject to change. But does anyone listen? No. - if ( isEvents && !thisCache[ name ] ) { - return privateCache.events; - } - - // Check for both converted-to-camel and non-converted data property names - // If a data property was specified - if ( getByName ) { - - // First Try to find as-is property data - ret = thisCache[ name ]; - - // Test for null|undefined property data - if ( ret == null ) { - - // Try to find the camelCased property - ret = thisCache[ jQuery.camelCase( name ) ]; - } - } else { - ret = thisCache; - } - - return ret; - }, - - removeData: function( elem, name, pvt /* Internal Use Only */ ) { - if ( !jQuery.acceptData( elem ) ) { - return; - } - - var thisCache, i, l, - - // Reference to internal data cache key - internalKey = jQuery.expando, - - isNode = elem.nodeType, - - // See jQuery.data for more information - cache = isNode ? jQuery.cache : elem, - - // See jQuery.data for more information - id = isNode ? elem[ internalKey ] : internalKey; - - // If there is already no cache entry for this object, there is no - // purpose in continuing - if ( !cache[ id ] ) { - return; - } - - if ( name ) { - - thisCache = pvt ? cache[ id ] : cache[ id ].data; - - if ( thisCache ) { - - // Support array or space separated string names for data keys - if ( !jQuery.isArray( name ) ) { - - // try the string as a key before any manipulation - if ( name in thisCache ) { - name = [ name ]; - } else { - - // split the camel cased version by spaces unless a key with the spaces exists - name = jQuery.camelCase( name ); - if ( name in thisCache ) { - name = [ name ]; - } else { - name = name.split( " " ); - } - } - } - - for ( i = 0, l = name.length; i < l; i++ ) { - delete thisCache[ name[i] ]; - } - - // If there is no data left in the cache, we want to continue - // and let the cache object itself get destroyed - if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { - return; - } - } - } - - // See jQuery.data for more information - if ( !pvt ) { - delete cache[ id ].data; - - // Don't destroy the parent cache unless the internal data object - // had been the only thing left in it - if ( !isEmptyDataObject(cache[ id ]) ) { - return; - } - } - - // Browsers that fail expando deletion also refuse to delete expandos on - // the window, but it will allow it on all other JS objects; other browsers - // don't care - // Ensure that `cache` is not a window object #10080 - if ( jQuery.support.deleteExpando || !cache.setInterval ) { - delete cache[ id ]; - } else { - cache[ id ] = null; - } - - // We destroyed the cache and need to eliminate the expando on the node to avoid - // false lookups in the cache for entries that no longer exist - if ( isNode ) { - // IE does not allow us to delete expando properties from nodes, - // nor does it have a removeAttribute function on Document nodes; - // we must handle all of these cases - if ( jQuery.support.deleteExpando ) { - delete elem[ internalKey ]; - } else if ( elem.removeAttribute ) { - elem.removeAttribute( internalKey ); - } else { - elem[ internalKey ] = null; - } - } - }, - - // For internal use only. - _data: function( elem, name, data ) { - return jQuery.data( elem, name, data, true ); - }, - - // A method for determining if a DOM node can handle the data expando - acceptData: function( elem ) { - if ( elem.nodeName ) { - var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; - - if ( match ) { - return !(match === true || elem.getAttribute("classid") !== match); - } - } - - return true; - } -}); - -jQuery.fn.extend({ - data: function( key, value ) { - var parts, part, attr, name, l, - elem = this[0], - i = 0, - data = null; - - // Gets all values - if ( key === undefined ) { - if ( this.length ) { - data = jQuery.data( elem ); - - if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { - attr = elem.attributes; - for ( l = attr.length; i < l; i++ ) { - name = attr[i].name; - - if ( name.indexOf( "data-" ) === 0 ) { - name = jQuery.camelCase( name.substring(5) ); - - dataAttr( elem, name, data[ name ] ); - } - } - jQuery._data( elem, "parsedAttrs", true ); - } - } - - return data; - } - - // Sets multiple values - if ( typeof key === "object" ) { - return this.each(function() { - jQuery.data( this, key ); - }); - } - - parts = key.split( ".", 2 ); - parts[1] = parts[1] ? "." + parts[1] : ""; - part = parts[1] + "!"; - - return jQuery.access( this, function( value ) { - - if ( value === undefined ) { - data = this.triggerHandler( "getData" + part, [ parts[0] ] ); - - // Try to fetch any internally stored data first - if ( data === undefined && elem ) { - data = jQuery.data( elem, key ); - data = dataAttr( elem, key, data ); - } - - return data === undefined && parts[1] ? - this.data( parts[0] ) : - data; - } - - parts[1] = value; - this.each(function() { - var self = jQuery( this ); - - self.triggerHandler( "setData" + part, parts ); - jQuery.data( this, key, value ); - self.triggerHandler( "changeData" + part, parts ); - }); - }, null, value, arguments.length > 1, null, false ); - }, - - removeData: function( key ) { - return this.each(function() { - jQuery.removeData( this, key ); - }); - } -}); - -function dataAttr( elem, key, data ) { - // If nothing was found internally, try to fetch any - // data from the HTML5 data-* attribute - if ( data === undefined && elem.nodeType === 1 ) { - - var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); - - data = elem.getAttribute( name ); - - if ( typeof data === "string" ) { - try { - data = data === "true" ? true : - data === "false" ? false : - data === "null" ? null : - jQuery.isNumeric( data ) ? +data : - rbrace.test( data ) ? jQuery.parseJSON( data ) : - data; - } catch( e ) {} - - // Make sure we set the data so it isn't changed later - jQuery.data( elem, key, data ); - - } else { - data = undefined; - } - } - - return data; -} - -// checks a cache object for emptiness -function isEmptyDataObject( obj ) { - for ( var name in obj ) { - - // if the public data object is empty, the private is still empty - if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { - continue; - } - if ( name !== "toJSON" ) { - return false; - } - } - - return true; -} - - - - -function handleQueueMarkDefer( elem, type, src ) { - var deferDataKey = type + "defer", - queueDataKey = type + "queue", - markDataKey = type + "mark", - defer = jQuery._data( elem, deferDataKey ); - if ( defer && - ( src === "queue" || !jQuery._data(elem, queueDataKey) ) && - ( src === "mark" || !jQuery._data(elem, markDataKey) ) ) { - // Give room for hard-coded callbacks to fire first - // and eventually mark/queue something else on the element - setTimeout( function() { - if ( !jQuery._data( elem, queueDataKey ) && - !jQuery._data( elem, markDataKey ) ) { - jQuery.removeData( elem, deferDataKey, true ); - defer.fire(); - } - }, 0 ); - } -} - -jQuery.extend({ - - _mark: function( elem, type ) { - if ( elem ) { - type = ( type || "fx" ) + "mark"; - jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 ); - } - }, - - _unmark: function( force, elem, type ) { - if ( force !== true ) { - type = elem; - elem = force; - force = false; - } - if ( elem ) { - type = type || "fx"; - var key = type + "mark", - count = force ? 0 : ( (jQuery._data( elem, key ) || 1) - 1 ); - if ( count ) { - jQuery._data( elem, key, count ); - } else { - jQuery.removeData( elem, key, true ); - handleQueueMarkDefer( elem, type, "mark" ); - } - } - }, - - queue: function( elem, type, data ) { - var q; - if ( elem ) { - type = ( type || "fx" ) + "queue"; - q = jQuery._data( elem, type ); - - // Speed up dequeue by getting out quickly if this is just a lookup - if ( data ) { - if ( !q || jQuery.isArray(data) ) { - q = jQuery._data( elem, type, jQuery.makeArray(data) ); - } else { - q.push( data ); - } - } - return q || []; - } - }, - - dequeue: function( elem, type ) { - type = type || "fx"; - - var queue = jQuery.queue( elem, type ), - fn = queue.shift(), - hooks = {}; - - // If the fx queue is dequeued, always remove the progress sentinel - if ( fn === "inprogress" ) { - fn = queue.shift(); - } - - if ( fn ) { - // Add a progress sentinel to prevent the fx queue from being - // automatically dequeued - if ( type === "fx" ) { - queue.unshift( "inprogress" ); - } - - jQuery._data( elem, type + ".run", hooks ); - fn.call( elem, function() { - jQuery.dequeue( elem, type ); - }, hooks ); - } - - if ( !queue.length ) { - jQuery.removeData( elem, type + "queue " + type + ".run", true ); - handleQueueMarkDefer( elem, type, "queue" ); - } - } -}); - -jQuery.fn.extend({ - queue: function( type, data ) { - var setter = 2; - - if ( typeof type !== "string" ) { - data = type; - type = "fx"; - setter--; - } - - if ( arguments.length < setter ) { - return jQuery.queue( this[0], type ); - } - - return data === undefined ? - this : - this.each(function() { - var queue = jQuery.queue( this, type, data ); - - if ( type === "fx" && queue[0] !== "inprogress" ) { - jQuery.dequeue( this, type ); - } - }); - }, - dequeue: function( type ) { - return this.each(function() { - jQuery.dequeue( this, type ); - }); - }, - // Based off of the plugin by Clint Helfers, with permission. - // http://blindsignals.com/index.php/2009/07/jquery-delay/ - delay: function( time, type ) { - time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; - type = type || "fx"; - - return this.queue( type, function( next, hooks ) { - var timeout = setTimeout( next, time ); - hooks.stop = function() { - clearTimeout( timeout ); - }; - }); - }, - clearQueue: function( type ) { - return this.queue( type || "fx", [] ); - }, - // Get a promise resolved when queues of a certain type - // are emptied (fx is the type by default) - promise: function( type, object ) { - if ( typeof type !== "string" ) { - object = type; - type = undefined; - } - type = type || "fx"; - var defer = jQuery.Deferred(), - elements = this, - i = elements.length, - count = 1, - deferDataKey = type + "defer", - queueDataKey = type + "queue", - markDataKey = type + "mark", - tmp; - function resolve() { - if ( !( --count ) ) { - defer.resolveWith( elements, [ elements ] ); - } - } - while( i-- ) { - if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) || - ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) || - jQuery.data( elements[ i ], markDataKey, undefined, true ) ) && - jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) )) { - count++; - tmp.add( resolve ); - } - } - resolve(); - return defer.promise( object ); - } -}); - - - - -var rclass = /[\n\t\r]/g, - rspace = /\s+/, - rreturn = /\r/g, - rtype = /^(?:button|input)$/i, - rfocusable = /^(?:button|input|object|select|textarea)$/i, - rclickable = /^a(?:rea)?$/i, - rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, - getSetAttribute = jQuery.support.getSetAttribute, - nodeHook, boolHook, fixSpecified; - -jQuery.fn.extend({ - attr: function( name, value ) { - return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); - }, - - removeAttr: function( name ) { - return this.each(function() { - jQuery.removeAttr( this, name ); - }); - }, - - prop: function( name, value ) { - return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); - }, - - removeProp: function( name ) { - name = jQuery.propFix[ name ] || name; - return this.each(function() { - // try/catch handles cases where IE balks (such as removing a property on window) - try { - this[ name ] = undefined; - delete this[ name ]; - } catch( e ) {} - }); - }, - - addClass: function( value ) { - var classNames, i, l, elem, - setClass, c, cl; - - if ( jQuery.isFunction( value ) ) { - return this.each(function( j ) { - jQuery( this ).addClass( value.call(this, j, this.className) ); - }); - } - - if ( value && typeof value === "string" ) { - classNames = value.split( rspace ); - - for ( i = 0, l = this.length; i < l; i++ ) { - elem = this[ i ]; - - if ( elem.nodeType === 1 ) { - if ( !elem.className && classNames.length === 1 ) { - elem.className = value; - - } else { - setClass = " " + elem.className + " "; - - for ( c = 0, cl = classNames.length; c < cl; c++ ) { - if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { - setClass += classNames[ c ] + " "; - } - } - elem.className = jQuery.trim( setClass ); - } - } - } - } - - return this; - }, - - removeClass: function( value ) { - var classNames, i, l, elem, className, c, cl; - - if ( jQuery.isFunction( value ) ) { - return this.each(function( j ) { - jQuery( this ).removeClass( value.call(this, j, this.className) ); - }); - } - - if ( (value && typeof value === "string") || value === undefined ) { - classNames = ( value || "" ).split( rspace ); - - for ( i = 0, l = this.length; i < l; i++ ) { - elem = this[ i ]; - - if ( elem.nodeType === 1 && elem.className ) { - if ( value ) { - className = (" " + elem.className + " ").replace( rclass, " " ); - for ( c = 0, cl = classNames.length; c < cl; c++ ) { - className = className.replace(" " + classNames[ c ] + " ", " "); - } - elem.className = jQuery.trim( className ); - - } else { - elem.className = ""; - } - } - } - } - - return this; - }, - - toggleClass: function( value, stateVal ) { - var type = typeof value, - isBool = typeof stateVal === "boolean"; - - if ( jQuery.isFunction( value ) ) { - return this.each(function( i ) { - jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); - }); - } - - return this.each(function() { - if ( type === "string" ) { - // toggle individual class names - var className, - i = 0, - self = jQuery( this ), - state = stateVal, - classNames = value.split( rspace ); - - while ( (className = classNames[ i++ ]) ) { - // check each className given, space seperated list - state = isBool ? state : !self.hasClass( className ); - self[ state ? "addClass" : "removeClass" ]( className ); - } - - } else if ( type === "undefined" || type === "boolean" ) { - if ( this.className ) { - // store className if set - jQuery._data( this, "__className__", this.className ); - } - - // toggle whole className - this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; - } - }); - }, - - hasClass: function( selector ) { - var className = " " + selector + " ", - i = 0, - l = this.length; - for ( ; i < l; i++ ) { - if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { - return true; - } - } - - return false; - }, - - val: function( value ) { - var hooks, ret, isFunction, - elem = this[0]; - - if ( !arguments.length ) { - if ( elem ) { - hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; - - if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { - return ret; - } - - ret = elem.value; - - return typeof ret === "string" ? - // handle most common string cases - ret.replace(rreturn, "") : - // handle cases where value is null/undef or number - ret == null ? "" : ret; - } - - return; - } - - isFunction = jQuery.isFunction( value ); - - return this.each(function( i ) { - var self = jQuery(this), val; - - if ( this.nodeType !== 1 ) { - return; - } - - if ( isFunction ) { - val = value.call( this, i, self.val() ); - } else { - val = value; - } - - // Treat null/undefined as ""; convert numbers to string - if ( val == null ) { - val = ""; - } else if ( typeof val === "number" ) { - val += ""; - } else if ( jQuery.isArray( val ) ) { - val = jQuery.map(val, function ( value ) { - return value == null ? "" : value + ""; - }); - } - - hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; - - // If set returns undefined, fall back to normal setting - if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { - this.value = val; - } - }); - } -}); - -jQuery.extend({ - valHooks: { - option: { - get: function( elem ) { - // attributes.value is undefined in Blackberry 4.7 but - // uses .value. See #6932 - var val = elem.attributes.value; - return !val || val.specified ? elem.value : elem.text; - } - }, - select: { - get: function( elem ) { - var value, i, max, option, - index = elem.selectedIndex, - values = [], - options = elem.options, - one = elem.type === "select-one"; - - // Nothing was selected - if ( index < 0 ) { - return null; - } - - // Loop through all the selected options - i = one ? index : 0; - max = one ? index + 1 : options.length; - for ( ; i < max; i++ ) { - option = options[ i ]; - - // Don't return options that are disabled or in a disabled optgroup - if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && - (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { - - // Get the specific value for the option - value = jQuery( option ).val(); - - // We don't need an array for one selects - if ( one ) { - return value; - } - - // Multi-Selects return an array - values.push( value ); - } - } - - // Fixes Bug #2551 -- select.val() broken in IE after form.reset() - if ( one && !values.length && options.length ) { - return jQuery( options[ index ] ).val(); - } - - return values; - }, - - set: function( elem, value ) { - var values = jQuery.makeArray( value ); - - jQuery(elem).find("option").each(function() { - this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; - }); - - if ( !values.length ) { - elem.selectedIndex = -1; - } - return values; - } - } - }, - - attrFn: { - val: true, - css: true, - html: true, - text: true, - data: true, - width: true, - height: true, - offset: true - }, - - attr: function( elem, name, value, pass ) { - var ret, hooks, notxml, - nType = elem.nodeType; - - // don't get/set attributes on text, comment and attribute nodes - if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { - return; - } - - if ( pass && name in jQuery.attrFn ) { - return jQuery( elem )[ name ]( value ); - } - - // Fallback to prop when attributes are not supported - if ( typeof elem.getAttribute === "undefined" ) { - return jQuery.prop( elem, name, value ); - } - - notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); - - // All attributes are lowercase - // Grab necessary hook if one is defined - if ( notxml ) { - name = name.toLowerCase(); - hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); - } - - if ( value !== undefined ) { - - if ( value === null ) { - jQuery.removeAttr( elem, name ); - return; - - } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { - return ret; - - } else { - elem.setAttribute( name, "" + value ); - return value; - } - - } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { - return ret; - - } else { - - ret = elem.getAttribute( name ); - - // Non-existent attributes return null, we normalize to undefined - return ret === null ? - undefined : - ret; - } - }, - - removeAttr: function( elem, value ) { - var propName, attrNames, name, l, isBool, - i = 0; - - if ( value && elem.nodeType === 1 ) { - attrNames = value.toLowerCase().split( rspace ); - l = attrNames.length; - - for ( ; i < l; i++ ) { - name = attrNames[ i ]; - - if ( name ) { - propName = jQuery.propFix[ name ] || name; - isBool = rboolean.test( name ); - - // See #9699 for explanation of this approach (setting first, then removal) - // Do not do this for boolean attributes (see #10870) - if ( !isBool ) { - jQuery.attr( elem, name, "" ); - } - elem.removeAttribute( getSetAttribute ? name : propName ); - - // Set corresponding property to false for boolean attributes - if ( isBool && propName in elem ) { - elem[ propName ] = false; - } - } - } - } - }, - - attrHooks: { - type: { - set: function( elem, value ) { - // We can't allow the type property to be changed (since it causes problems in IE) - if ( rtype.test( elem.nodeName ) && elem.parentNode ) { - jQuery.error( "type property can't be changed" ); - } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { - // Setting the type on a radio button after the value resets the value in IE6-9 - // Reset value to it's default in case type is set after value - // This is for element creation - var val = elem.value; - elem.setAttribute( "type", value ); - if ( val ) { - elem.value = val; - } - return value; - } - } - }, - // Use the value property for back compat - // Use the nodeHook for button elements in IE6/7 (#1954) - value: { - get: function( elem, name ) { - if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { - return nodeHook.get( elem, name ); - } - return name in elem ? - elem.value : - null; - }, - set: function( elem, value, name ) { - if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { - return nodeHook.set( elem, value, name ); - } - // Does not return so that setAttribute is also used - elem.value = value; - } - } - }, - - propFix: { - tabindex: "tabIndex", - readonly: "readOnly", - "for": "htmlFor", - "class": "className", - maxlength: "maxLength", - cellspacing: "cellSpacing", - cellpadding: "cellPadding", - rowspan: "rowSpan", - colspan: "colSpan", - usemap: "useMap", - frameborder: "frameBorder", - contenteditable: "contentEditable" - }, - - prop: function( elem, name, value ) { - var ret, hooks, notxml, - nType = elem.nodeType; - - // don't get/set properties on text, comment and attribute nodes - if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { - return; - } - - notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); - - if ( notxml ) { - // Fix name and attach hooks - name = jQuery.propFix[ name ] || name; - hooks = jQuery.propHooks[ name ]; - } - - if ( value !== undefined ) { - if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { - return ret; - - } else { - return ( elem[ name ] = value ); - } - - } else { - if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { - return ret; - - } else { - return elem[ name ]; - } - } - }, - - propHooks: { - tabIndex: { - get: function( elem ) { - // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set - // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ - var attributeNode = elem.getAttributeNode("tabindex"); - - return attributeNode && attributeNode.specified ? - parseInt( attributeNode.value, 10 ) : - rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? - 0 : - undefined; - } - } - } -}); - -// Add the tabIndex propHook to attrHooks for back-compat (different case is intentional) -jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex; - -// Hook for boolean attributes -boolHook = { - get: function( elem, name ) { - // Align boolean attributes with corresponding properties - // Fall back to attribute presence where some booleans are not supported - var attrNode, - property = jQuery.prop( elem, name ); - return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? - name.toLowerCase() : - undefined; - }, - set: function( elem, value, name ) { - var propName; - if ( value === false ) { - // Remove boolean attributes when set to false - jQuery.removeAttr( elem, name ); - } else { - // value is true since we know at this point it's type boolean and not false - // Set boolean attributes to the same name and set the DOM property - propName = jQuery.propFix[ name ] || name; - if ( propName in elem ) { - // Only set the IDL specifically if it already exists on the element - elem[ propName ] = true; - } - - elem.setAttribute( name, name.toLowerCase() ); - } - return name; - } -}; - -// IE6/7 do not support getting/setting some attributes with get/setAttribute -if ( !getSetAttribute ) { - - fixSpecified = { - name: true, - id: true, - coords: true - }; - - // Use this for any attribute in IE6/7 - // This fixes almost every IE6/7 issue - nodeHook = jQuery.valHooks.button = { - get: function( elem, name ) { - var ret; - ret = elem.getAttributeNode( name ); - return ret && ( fixSpecified[ name ] ? ret.nodeValue !== "" : ret.specified ) ? - ret.nodeValue : - undefined; - }, - set: function( elem, value, name ) { - // Set the existing or create a new attribute node - var ret = elem.getAttributeNode( name ); - if ( !ret ) { - ret = document.createAttribute( name ); - elem.setAttributeNode( ret ); - } - return ( ret.nodeValue = value + "" ); - } - }; - - // Apply the nodeHook to tabindex - jQuery.attrHooks.tabindex.set = nodeHook.set; - - // Set width and height to auto instead of 0 on empty string( Bug #8150 ) - // This is for removals - jQuery.each([ "width", "height" ], function( i, name ) { - jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { - set: function( elem, value ) { - if ( value === "" ) { - elem.setAttribute( name, "auto" ); - return value; - } - } - }); - }); - - // Set contenteditable to false on removals(#10429) - // Setting to empty string throws an error as an invalid value - jQuery.attrHooks.contenteditable = { - get: nodeHook.get, - set: function( elem, value, name ) { - if ( value === "" ) { - value = "false"; - } - nodeHook.set( elem, value, name ); - } - }; -} - - -// Some attributes require a special call on IE -if ( !jQuery.support.hrefNormalized ) { - jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { - jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { - get: function( elem ) { - var ret = elem.getAttribute( name, 2 ); - return ret === null ? undefined : ret; - } - }); - }); -} - -if ( !jQuery.support.style ) { - jQuery.attrHooks.style = { - get: function( elem ) { - // Return undefined in the case of empty string - // Normalize to lowercase since IE uppercases css property names - return elem.style.cssText.toLowerCase() || undefined; - }, - set: function( elem, value ) { - return ( elem.style.cssText = "" + value ); - } - }; -} - -// Safari mis-reports the default selected property of an option -// Accessing the parent's selectedIndex property fixes it -if ( !jQuery.support.optSelected ) { - jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { - get: function( elem ) { - var parent = elem.parentNode; - - if ( parent ) { - parent.selectedIndex; - - // Make sure that it also works with optgroups, see #5701 - if ( parent.parentNode ) { - parent.parentNode.selectedIndex; - } - } - return null; - } - }); -} - -// IE6/7 call enctype encoding -if ( !jQuery.support.enctype ) { - jQuery.propFix.enctype = "encoding"; -} - -// Radios and checkboxes getter/setter -if ( !jQuery.support.checkOn ) { - jQuery.each([ "radio", "checkbox" ], function() { - jQuery.valHooks[ this ] = { - get: function( elem ) { - // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified - return elem.getAttribute("value") === null ? "on" : elem.value; - } - }; - }); -} -jQuery.each([ "radio", "checkbox" ], function() { - jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { - set: function( elem, value ) { - if ( jQuery.isArray( value ) ) { - return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); - } - } - }); -}); - - - - -var rformElems = /^(?:textarea|input|select)$/i, - rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/, - rhoverHack = /(?:^|\s)hover(\.\S+)?\b/, - rkeyEvent = /^key/, - rmouseEvent = /^(?:mouse|contextmenu)|click/, - rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, - rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/, - quickParse = function( selector ) { - var quick = rquickIs.exec( selector ); - if ( quick ) { - // 0 1 2 3 - // [ _, tag, id, class ] - quick[1] = ( quick[1] || "" ).toLowerCase(); - quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" ); - } - return quick; - }, - quickIs = function( elem, m ) { - var attrs = elem.attributes || {}; - return ( - (!m[1] || elem.nodeName.toLowerCase() === m[1]) && - (!m[2] || (attrs.id || {}).value === m[2]) && - (!m[3] || m[3].test( (attrs[ "class" ] || {}).value )) - ); - }, - hoverHack = function( events ) { - return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); - }; - -/* - * Helper functions for managing events -- not part of the public interface. - * Props to Dean Edwards' addEvent library for many of the ideas. - */ -jQuery.event = { - - add: function( elem, types, handler, data, selector ) { - - var elemData, eventHandle, events, - t, tns, type, namespaces, handleObj, - handleObjIn, quick, handlers, special; - - // Don't attach events to noData or text/comment nodes (allow plain objects tho) - if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { - return; - } - - // Caller can pass in an object of custom data in lieu of the handler - if ( handler.handler ) { - handleObjIn = handler; - handler = handleObjIn.handler; - selector = handleObjIn.selector; - } - - // Make sure that the handler has a unique ID, used to find/remove it later - if ( !handler.guid ) { - handler.guid = jQuery.guid++; - } - - // Init the element's event structure and main handler, if this is the first - events = elemData.events; - if ( !events ) { - elemData.events = events = {}; - } - eventHandle = elemData.handle; - if ( !eventHandle ) { - elemData.handle = eventHandle = function( e ) { - // Discard the second event of a jQuery.event.trigger() and - // when an event is called after a page has unloaded - return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? - jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : - undefined; - }; - // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events - eventHandle.elem = elem; - } - - // Handle multiple events separated by a space - // jQuery(...).bind("mouseover mouseout", fn); - types = jQuery.trim( hoverHack(types) ).split( " " ); - for ( t = 0; t < types.length; t++ ) { - - tns = rtypenamespace.exec( types[t] ) || []; - type = tns[1]; - namespaces = ( tns[2] || "" ).split( "." ).sort(); - - // If event changes its type, use the special event handlers for the changed type - special = jQuery.event.special[ type ] || {}; - - // If selector defined, determine special event api type, otherwise given type - type = ( selector ? special.delegateType : special.bindType ) || type; - - // Update special based on newly reset type - special = jQuery.event.special[ type ] || {}; - - // handleObj is passed to all event handlers - handleObj = jQuery.extend({ - type: type, - origType: tns[1], - data: data, - handler: handler, - guid: handler.guid, - selector: selector, - quick: selector && quickParse( selector ), - namespace: namespaces.join(".") - }, handleObjIn ); - - // Init the event handler queue if we're the first - handlers = events[ type ]; - if ( !handlers ) { - handlers = events[ type ] = []; - handlers.delegateCount = 0; - - // Only use addEventListener/attachEvent if the special events handler returns false - if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { - // Bind the global event handler to the element - if ( elem.addEventListener ) { - elem.addEventListener( type, eventHandle, false ); - - } else if ( elem.attachEvent ) { - elem.attachEvent( "on" + type, eventHandle ); - } - } - } - - if ( special.add ) { - special.add.call( elem, handleObj ); - - if ( !handleObj.handler.guid ) { - handleObj.handler.guid = handler.guid; - } - } - - // Add to the element's handler list, delegates in front - if ( selector ) { - handlers.splice( handlers.delegateCount++, 0, handleObj ); - } else { - handlers.push( handleObj ); - } - - // Keep track of which events have ever been used, for event optimization - jQuery.event.global[ type ] = true; - } - - // Nullify elem to prevent memory leaks in IE - elem = null; - }, - - global: {}, - - // Detach an event or set of events from an element - remove: function( elem, types, handler, selector, mappedTypes ) { - - var elemData = jQuery.hasData( elem ) && jQuery._data( elem ), - t, tns, type, origType, namespaces, origCount, - j, events, special, handle, eventType, handleObj; - - if ( !elemData || !(events = elemData.events) ) { - return; - } - - // Once for each type.namespace in types; type may be omitted - types = jQuery.trim( hoverHack( types || "" ) ).split(" "); - for ( t = 0; t < types.length; t++ ) { - tns = rtypenamespace.exec( types[t] ) || []; - type = origType = tns[1]; - namespaces = tns[2]; - - // Unbind all events (on this namespace, if provided) for the element - if ( !type ) { - for ( type in events ) { - jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); - } - continue; - } - - special = jQuery.event.special[ type ] || {}; - type = ( selector? special.delegateType : special.bindType ) || type; - eventType = events[ type ] || []; - origCount = eventType.length; - namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null; - - // Remove matching events - for ( j = 0; j < eventType.length; j++ ) { - handleObj = eventType[ j ]; - - if ( ( mappedTypes || origType === handleObj.origType ) && - ( !handler || handler.guid === handleObj.guid ) && - ( !namespaces || namespaces.test( handleObj.namespace ) ) && - ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { - eventType.splice( j--, 1 ); - - if ( handleObj.selector ) { - eventType.delegateCount--; - } - if ( special.remove ) { - special.remove.call( elem, handleObj ); - } - } - } - - // Remove generic event handler if we removed something and no more handlers exist - // (avoids potential for endless recursion during removal of special event handlers) - if ( eventType.length === 0 && origCount !== eventType.length ) { - if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { - jQuery.removeEvent( elem, type, elemData.handle ); - } - - delete events[ type ]; - } - } - - // Remove the expando if it's no longer used - if ( jQuery.isEmptyObject( events ) ) { - handle = elemData.handle; - if ( handle ) { - handle.elem = null; - } - - // removeData also checks for emptiness and clears the expando if empty - // so use it instead of delete - jQuery.removeData( elem, [ "events", "handle" ], true ); - } - }, - - // Events that are safe to short-circuit if no handlers are attached. - // Native DOM events should not be added, they may have inline handlers. - customEvent: { - "getData": true, - "setData": true, - "changeData": true - }, - - trigger: function( event, data, elem, onlyHandlers ) { - // Don't do events on text and comment nodes - if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { - return; - } - - // Event object or event type - var type = event.type || event, - namespaces = [], - cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType; - - // focus/blur morphs to focusin/out; ensure we're not firing them right now - if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { - return; - } - - if ( type.indexOf( "!" ) >= 0 ) { - // Exclusive events trigger only for the exact event (no namespaces) - type = type.slice(0, -1); - exclusive = true; - } - - if ( type.indexOf( "." ) >= 0 ) { - // Namespaced trigger; create a regexp to match event type in handle() - namespaces = type.split("."); - type = namespaces.shift(); - namespaces.sort(); - } - - if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { - // No jQuery handlers for this event type, and it can't have inline handlers - return; - } - - // Caller can pass in an Event, Object, or just an event type string - event = typeof event === "object" ? - // jQuery.Event object - event[ jQuery.expando ] ? event : - // Object literal - new jQuery.Event( type, event ) : - // Just the event type (string) - new jQuery.Event( type ); - - event.type = type; - event.isTrigger = true; - event.exclusive = exclusive; - event.namespace = namespaces.join( "." ); - event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null; - ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; - - // Handle a global trigger - if ( !elem ) { - - // TODO: Stop taunting the data cache; remove global events and always attach to document - cache = jQuery.cache; - for ( i in cache ) { - if ( cache[ i ].events && cache[ i ].events[ type ] ) { - jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); - } - } - return; - } - - // Clean up the event in case it is being reused - event.result = undefined; - if ( !event.target ) { - event.target = elem; - } - - // Clone any incoming data and prepend the event, creating the handler arg list - data = data != null ? jQuery.makeArray( data ) : []; - data.unshift( event ); - - // Allow special events to draw outside the lines - special = jQuery.event.special[ type ] || {}; - if ( special.trigger && special.trigger.apply( elem, data ) === false ) { - return; - } - - // Determine event propagation path in advance, per W3C events spec (#9951) - // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) - eventPath = [[ elem, special.bindType || type ]]; - if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { - - bubbleType = special.delegateType || type; - cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; - old = null; - for ( ; cur; cur = cur.parentNode ) { - eventPath.push([ cur, bubbleType ]); - old = cur; - } - - // Only add window if we got to document (e.g., not plain obj or detached DOM) - if ( old && old === elem.ownerDocument ) { - eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); - } - } - - // Fire handlers on the event path - for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { - - cur = eventPath[i][0]; - event.type = eventPath[i][1]; - - handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); - if ( handle ) { - handle.apply( cur, data ); - } - // Note that this is a bare JS function and not a jQuery handler - handle = ontype && cur[ ontype ]; - if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) { - event.preventDefault(); - } - } - event.type = type; - - // If nobody prevented the default action, do it now - if ( !onlyHandlers && !event.isDefaultPrevented() ) { - - if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && - !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { - - // Call a native DOM method on the target with the same name name as the event. - // Can't use an .isFunction() check here because IE6/7 fails that test. - // Don't do default actions on window, that's where global variables be (#6170) - // IE<9 dies on focus/blur to hidden element (#1486) - if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { - - // Don't re-trigger an onFOO event when we call its FOO() method - old = elem[ ontype ]; - - if ( old ) { - elem[ ontype ] = null; - } - - // Prevent re-triggering of the same event, since we already bubbled it above - jQuery.event.triggered = type; - elem[ type ](); - jQuery.event.triggered = undefined; - - if ( old ) { - elem[ ontype ] = old; - } - } - } - } - - return event.result; - }, - - dispatch: function( event ) { - - // Make a writable jQuery.Event from the native event object - event = jQuery.event.fix( event || window.event ); - - var handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), - delegateCount = handlers.delegateCount, - args = [].slice.call( arguments, 0 ), - run_all = !event.exclusive && !event.namespace, - special = jQuery.event.special[ event.type ] || {}, - handlerQueue = [], - i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related; - - // Use the fix-ed jQuery.Event rather than the (read-only) native event - args[0] = event; - event.delegateTarget = this; - - // Call the preDispatch hook for the mapped type, and let it bail if desired - if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { - return; - } - - // Determine handlers that should run if there are delegated events - // Avoid non-left-click bubbling in Firefox (#3861) - if ( delegateCount && !(event.button && event.type === "click") ) { - - // Pregenerate a single jQuery object for reuse with .is() - jqcur = jQuery(this); - jqcur.context = this.ownerDocument || this; - - for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { - - // Don't process events on disabled elements (#6911, #8165) - if ( cur.disabled !== true ) { - selMatch = {}; - matches = []; - jqcur[0] = cur; - for ( i = 0; i < delegateCount; i++ ) { - handleObj = handlers[ i ]; - sel = handleObj.selector; - - if ( selMatch[ sel ] === undefined ) { - selMatch[ sel ] = ( - handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel ) - ); - } - if ( selMatch[ sel ] ) { - matches.push( handleObj ); - } - } - if ( matches.length ) { - handlerQueue.push({ elem: cur, matches: matches }); - } - } - } - } - - // Add the remaining (directly-bound) handlers - if ( handlers.length > delegateCount ) { - handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); - } - - // Run delegates first; they may want to stop propagation beneath us - for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { - matched = handlerQueue[ i ]; - event.currentTarget = matched.elem; - - for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { - handleObj = matched.matches[ j ]; - - // Triggered event must either 1) be non-exclusive and have no namespace, or - // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). - if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { - - event.data = handleObj.data; - event.handleObj = handleObj; - - ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) - .apply( matched.elem, args ); - - if ( ret !== undefined ) { - event.result = ret; - if ( ret === false ) { - event.preventDefault(); - event.stopPropagation(); - } - } - } - } - } - - // Call the postDispatch hook for the mapped type - if ( special.postDispatch ) { - special.postDispatch.call( this, event ); - } - - return event.result; - }, - - // Includes some event props shared by KeyEvent and MouseEvent - // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** - props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), - - fixHooks: {}, - - keyHooks: { - props: "char charCode key keyCode".split(" "), - filter: function( event, original ) { - - // Add which for key events - if ( event.which == null ) { - event.which = original.charCode != null ? original.charCode : original.keyCode; - } - - return event; - } - }, - - mouseHooks: { - props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), - filter: function( event, original ) { - var eventDoc, doc, body, - button = original.button, - fromElement = original.fromElement; - - // Calculate pageX/Y if missing and clientX/Y available - if ( event.pageX == null && original.clientX != null ) { - eventDoc = event.target.ownerDocument || document; - doc = eventDoc.documentElement; - body = eventDoc.body; - - event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); - event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); - } - - // Add relatedTarget, if necessary - if ( !event.relatedTarget && fromElement ) { - event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; - } - - // Add which for click: 1 === left; 2 === middle; 3 === right - // Note: button is not normalized, so don't use it - if ( !event.which && button !== undefined ) { - event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); - } - - return event; - } - }, - - fix: function( event ) { - if ( event[ jQuery.expando ] ) { - return event; - } - - // Create a writable copy of the event object and normalize some properties - var i, prop, - originalEvent = event, - fixHook = jQuery.event.fixHooks[ event.type ] || {}, - copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; - - event = jQuery.Event( originalEvent ); - - for ( i = copy.length; i; ) { - prop = copy[ --i ]; - event[ prop ] = originalEvent[ prop ]; - } - - // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) - if ( !event.target ) { - event.target = originalEvent.srcElement || document; - } - - // Target should not be a text node (#504, Safari) - if ( event.target.nodeType === 3 ) { - event.target = event.target.parentNode; - } - - // For mouse/key events; add metaKey if it's not there (#3368, IE6/7/8) - if ( event.metaKey === undefined ) { - event.metaKey = event.ctrlKey; - } - - return fixHook.filter? fixHook.filter( event, originalEvent ) : event; - }, - - special: { - ready: { - // Make sure the ready event is setup - setup: jQuery.bindReady - }, - - load: { - // Prevent triggered image.load events from bubbling to window.load - noBubble: true - }, - - focus: { - delegateType: "focusin" - }, - blur: { - delegateType: "focusout" - }, - - beforeunload: { - setup: function( data, namespaces, eventHandle ) { - // We only want to do this special case on windows - if ( jQuery.isWindow( this ) ) { - this.onbeforeunload = eventHandle; - } - }, - - teardown: function( namespaces, eventHandle ) { - if ( this.onbeforeunload === eventHandle ) { - this.onbeforeunload = null; - } - } - } - }, - - simulate: function( type, elem, event, bubble ) { - // Piggyback on a donor event to simulate a different one. - // Fake originalEvent to avoid donor's stopPropagation, but if the - // simulated event prevents default then we do the same on the donor. - var e = jQuery.extend( - new jQuery.Event(), - event, - { type: type, - isSimulated: true, - originalEvent: {} - } - ); - if ( bubble ) { - jQuery.event.trigger( e, null, elem ); - } else { - jQuery.event.dispatch.call( elem, e ); - } - if ( e.isDefaultPrevented() ) { - event.preventDefault(); - } - } -}; - -// Some plugins are using, but it's undocumented/deprecated and will be removed. -// The 1.7 special event interface should provide all the hooks needed now. -jQuery.event.handle = jQuery.event.dispatch; - -jQuery.removeEvent = document.removeEventListener ? - function( elem, type, handle ) { - if ( elem.removeEventListener ) { - elem.removeEventListener( type, handle, false ); - } - } : - function( elem, type, handle ) { - if ( elem.detachEvent ) { - elem.detachEvent( "on" + type, handle ); - } - }; - -jQuery.Event = function( src, props ) { - // Allow instantiation without the 'new' keyword - if ( !(this instanceof jQuery.Event) ) { - return new jQuery.Event( src, props ); - } - - // Event object - if ( src && src.type ) { - this.originalEvent = src; - this.type = src.type; - - // Events bubbling up the document may have been marked as prevented - // by a handler lower down the tree; reflect the correct value. - this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || - src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; - - // Event type - } else { - this.type = src; - } - - // Put explicitly provided properties onto the event object - if ( props ) { - jQuery.extend( this, props ); - } - - // Create a timestamp if incoming event doesn't have one - this.timeStamp = src && src.timeStamp || jQuery.now(); - - // Mark it as fixed - this[ jQuery.expando ] = true; -}; - -function returnFalse() { - return false; -} -function returnTrue() { - return true; -} - -// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding -// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html -jQuery.Event.prototype = { - preventDefault: function() { - this.isDefaultPrevented = returnTrue; - - var e = this.originalEvent; - if ( !e ) { - return; - } - - // if preventDefault exists run it on the original event - if ( e.preventDefault ) { - e.preventDefault(); - - // otherwise set the returnValue property of the original event to false (IE) - } else { - e.returnValue = false; - } - }, - stopPropagation: function() { - this.isPropagationStopped = returnTrue; - - var e = this.originalEvent; - if ( !e ) { - return; - } - // if stopPropagation exists run it on the original event - if ( e.stopPropagation ) { - e.stopPropagation(); - } - // otherwise set the cancelBubble property of the original event to true (IE) - e.cancelBubble = true; - }, - stopImmediatePropagation: function() { - this.isImmediatePropagationStopped = returnTrue; - this.stopPropagation(); - }, - isDefaultPrevented: returnFalse, - isPropagationStopped: returnFalse, - isImmediatePropagationStopped: returnFalse -}; - -// Create mouseenter/leave events using mouseover/out and event-time checks -jQuery.each({ - mouseenter: "mouseover", - mouseleave: "mouseout" -}, function( orig, fix ) { - jQuery.event.special[ orig ] = { - delegateType: fix, - bindType: fix, - - handle: function( event ) { - var target = this, - related = event.relatedTarget, - handleObj = event.handleObj, - selector = handleObj.selector, - ret; - - // For mousenter/leave call the handler if related is outside the target. - // NB: No relatedTarget if the mouse left/entered the browser window - if ( !related || (related !== target && !jQuery.contains( target, related )) ) { - event.type = handleObj.origType; - ret = handleObj.handler.apply( this, arguments ); - event.type = fix; - } - return ret; - } - }; -}); - -// IE submit delegation -if ( !jQuery.support.submitBubbles ) { - - jQuery.event.special.submit = { - setup: function() { - // Only need this for delegated form submit events - if ( jQuery.nodeName( this, "form" ) ) { - return false; - } - - // Lazy-add a submit handler when a descendant form may potentially be submitted - jQuery.event.add( this, "click._submit keypress._submit", function( e ) { - // Node name check avoids a VML-related crash in IE (#9807) - var elem = e.target, - form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; - if ( form && !form._submit_attached ) { - jQuery.event.add( form, "submit._submit", function( event ) { - event._submit_bubble = true; - }); - form._submit_attached = true; - } - }); - // return undefined since we don't need an event listener - }, - - postDispatch: function( event ) { - // If form was submitted by the user, bubble the event up the tree - if ( event._submit_bubble ) { - delete event._submit_bubble; - if ( this.parentNode && !event.isTrigger ) { - jQuery.event.simulate( "submit", this.parentNode, event, true ); - } - } - }, - - teardown: function() { - // Only need this for delegated form submit events - if ( jQuery.nodeName( this, "form" ) ) { - return false; - } - - // Remove delegated handlers; cleanData eventually reaps submit handlers attached above - jQuery.event.remove( this, "._submit" ); - } - }; -} - -// IE change delegation and checkbox/radio fix -if ( !jQuery.support.changeBubbles ) { - - jQuery.event.special.change = { - - setup: function() { - - if ( rformElems.test( this.nodeName ) ) { - // IE doesn't fire change on a check/radio until blur; trigger it on click - // after a propertychange. Eat the blur-change in special.change.handle. - // This still fires onchange a second time for check/radio after blur. - if ( this.type === "checkbox" || this.type === "radio" ) { - jQuery.event.add( this, "propertychange._change", function( event ) { - if ( event.originalEvent.propertyName === "checked" ) { - this._just_changed = true; - } - }); - jQuery.event.add( this, "click._change", function( event ) { - if ( this._just_changed && !event.isTrigger ) { - this._just_changed = false; - jQuery.event.simulate( "change", this, event, true ); - } - }); - } - return false; - } - // Delegated event; lazy-add a change handler on descendant inputs - jQuery.event.add( this, "beforeactivate._change", function( e ) { - var elem = e.target; - - if ( rformElems.test( elem.nodeName ) && !elem._change_attached ) { - jQuery.event.add( elem, "change._change", function( event ) { - if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { - jQuery.event.simulate( "change", this.parentNode, event, true ); - } - }); - elem._change_attached = true; - } - }); - }, - - handle: function( event ) { - var elem = event.target; - - // Swallow native change events from checkbox/radio, we already triggered them above - if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { - return event.handleObj.handler.apply( this, arguments ); - } - }, - - teardown: function() { - jQuery.event.remove( this, "._change" ); - - return rformElems.test( this.nodeName ); - } - }; -} - -// Create "bubbling" focus and blur events -if ( !jQuery.support.focusinBubbles ) { - jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { - - // Attach a single capturing handler while someone wants focusin/focusout - var attaches = 0, - handler = function( event ) { - jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); - }; - - jQuery.event.special[ fix ] = { - setup: function() { - if ( attaches++ === 0 ) { - document.addEventListener( orig, handler, true ); - } - }, - teardown: function() { - if ( --attaches === 0 ) { - document.removeEventListener( orig, handler, true ); - } - } - }; - }); -} - -jQuery.fn.extend({ - - on: function( types, selector, data, fn, /*INTERNAL*/ one ) { - var origFn, type; - - // Types can be a map of types/handlers - if ( typeof types === "object" ) { - // ( types-Object, selector, data ) - if ( typeof selector !== "string" ) { // && selector != null - // ( types-Object, data ) - data = data || selector; - selector = undefined; - } - for ( type in types ) { - this.on( type, selector, data, types[ type ], one ); - } - return this; - } - - if ( data == null && fn == null ) { - // ( types, fn ) - fn = selector; - data = selector = undefined; - } else if ( fn == null ) { - if ( typeof selector === "string" ) { - // ( types, selector, fn ) - fn = data; - data = undefined; - } else { - // ( types, data, fn ) - fn = data; - data = selector; - selector = undefined; - } - } - if ( fn === false ) { - fn = returnFalse; - } else if ( !fn ) { - return this; - } - - if ( one === 1 ) { - origFn = fn; - fn = function( event ) { - // Can use an empty set, since event contains the info - jQuery().off( event ); - return origFn.apply( this, arguments ); - }; - // Use same guid so caller can remove using origFn - fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); - } - return this.each( function() { - jQuery.event.add( this, types, fn, data, selector ); - }); - }, - one: function( types, selector, data, fn ) { - return this.on( types, selector, data, fn, 1 ); - }, - off: function( types, selector, fn ) { - if ( types && types.preventDefault && types.handleObj ) { - // ( event ) dispatched jQuery.Event - var handleObj = types.handleObj; - jQuery( types.delegateTarget ).off( - handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, - handleObj.selector, - handleObj.handler - ); - return this; - } - if ( typeof types === "object" ) { - // ( types-object [, selector] ) - for ( var type in types ) { - this.off( type, selector, types[ type ] ); - } - return this; - } - if ( selector === false || typeof selector === "function" ) { - // ( types [, fn] ) - fn = selector; - selector = undefined; - } - if ( fn === false ) { - fn = returnFalse; - } - return this.each(function() { - jQuery.event.remove( this, types, fn, selector ); - }); - }, - - bind: function( types, data, fn ) { - return this.on( types, null, data, fn ); - }, - unbind: function( types, fn ) { - return this.off( types, null, fn ); - }, - - live: function( types, data, fn ) { - jQuery( this.context ).on( types, this.selector, data, fn ); - return this; - }, - die: function( types, fn ) { - jQuery( this.context ).off( types, this.selector || "**", fn ); - return this; - }, - - delegate: function( selector, types, data, fn ) { - return this.on( types, selector, data, fn ); - }, - undelegate: function( selector, types, fn ) { - // ( namespace ) or ( selector, types [, fn] ) - return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn ); - }, - - trigger: function( type, data ) { - return this.each(function() { - jQuery.event.trigger( type, data, this ); - }); - }, - triggerHandler: function( type, data ) { - if ( this[0] ) { - return jQuery.event.trigger( type, data, this[0], true ); - } - }, - - toggle: function( fn ) { - // Save reference to arguments for access in closure - var args = arguments, - guid = fn.guid || jQuery.guid++, - i = 0, - toggler = function( event ) { - // Figure out which function to execute - var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; - jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); - - // Make sure that clicks stop - event.preventDefault(); - - // and execute the function - return args[ lastToggle ].apply( this, arguments ) || false; - }; - - // link all the functions, so any of them can unbind this click handler - toggler.guid = guid; - while ( i < args.length ) { - args[ i++ ].guid = guid; - } - - return this.click( toggler ); - }, - - hover: function( fnOver, fnOut ) { - return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); - } -}); - -jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + - "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + - "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { - - // Handle event binding - jQuery.fn[ name ] = function( data, fn ) { - if ( fn == null ) { - fn = data; - data = null; - } - - return arguments.length > 0 ? - this.on( name, null, data, fn ) : - this.trigger( name ); - }; - - if ( jQuery.attrFn ) { - jQuery.attrFn[ name ] = true; - } - - if ( rkeyEvent.test( name ) ) { - jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; - } - - if ( rmouseEvent.test( name ) ) { - jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; - } -}); - - - -/*! - * Sizzle CSS Selector Engine - * Copyright 2011, The Dojo Foundation - * Released under the MIT, BSD, and GPL Licenses. - * More information: http://sizzlejs.com/ - */ -(function(){ - -var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, - expando = "sizcache" + (Math.random() + '').replace('.', ''), - done = 0, - toString = Object.prototype.toString, - hasDuplicate = false, - baseHasDuplicate = true, - rBackslash = /\\/g, - rReturn = /\r\n/g, - rNonWord = /\W/; - -// Here we check if the JavaScript engine is using some sort of -// optimization where it does not always call our comparision -// function. If that is the case, discard the hasDuplicate value. -// Thus far that includes Google Chrome. -[0, 0].sort(function() { - baseHasDuplicate = false; - return 0; -}); - -var Sizzle = function( selector, context, results, seed ) { - results = results || []; - context = context || document; - - var origContext = context; - - if ( context.nodeType !== 1 && context.nodeType !== 9 ) { - return []; - } - - if ( !selector || typeof selector !== "string" ) { - return results; - } - - var m, set, checkSet, extra, ret, cur, pop, i, - prune = true, - contextXML = Sizzle.isXML( context ), - parts = [], - soFar = selector; - - // Reset the position of the chunker regexp (start from head) - do { - chunker.exec( "" ); - m = chunker.exec( soFar ); - - if ( m ) { - soFar = m[3]; - - parts.push( m[1] ); - - if ( m[2] ) { - extra = m[3]; - break; - } - } - } while ( m ); - - if ( parts.length > 1 && origPOS.exec( selector ) ) { - - if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { - set = posProcess( parts[0] + parts[1], context, seed ); - - } else { - set = Expr.relative[ parts[0] ] ? - [ context ] : - Sizzle( parts.shift(), context ); - - while ( parts.length ) { - selector = parts.shift(); - - if ( Expr.relative[ selector ] ) { - selector += parts.shift(); - } - - set = posProcess( selector, set, seed ); - } - } - - } else { - // Take a shortcut and set the context if the root selector is an ID - // (but not if it'll be faster if the inner selector is an ID) - if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && - Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { - - ret = Sizzle.find( parts.shift(), context, contextXML ); - context = ret.expr ? - Sizzle.filter( ret.expr, ret.set )[0] : - ret.set[0]; - } - - if ( context ) { - ret = seed ? - { expr: parts.pop(), set: makeArray(seed) } : - Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); - - set = ret.expr ? - Sizzle.filter( ret.expr, ret.set ) : - ret.set; - - if ( parts.length > 0 ) { - checkSet = makeArray( set ); - - } else { - prune = false; - } - - while ( parts.length ) { - cur = parts.pop(); - pop = cur; - - if ( !Expr.relative[ cur ] ) { - cur = ""; - } else { - pop = parts.pop(); - } - - if ( pop == null ) { - pop = context; - } - - Expr.relative[ cur ]( checkSet, pop, contextXML ); - } - - } else { - checkSet = parts = []; - } - } - - if ( !checkSet ) { - checkSet = set; - } - - if ( !checkSet ) { - Sizzle.error( cur || selector ); - } - - if ( toString.call(checkSet) === "[object Array]" ) { - if ( !prune ) { - results.push.apply( results, checkSet ); - - } else if ( context && context.nodeType === 1 ) { - for ( i = 0; checkSet[i] != null; i++ ) { - if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { - results.push( set[i] ); - } - } - - } else { - for ( i = 0; checkSet[i] != null; i++ ) { - if ( checkSet[i] && checkSet[i].nodeType === 1 ) { - results.push( set[i] ); - } - } - } - - } else { - makeArray( checkSet, results ); - } - - if ( extra ) { - Sizzle( extra, origContext, results, seed ); - Sizzle.uniqueSort( results ); - } - - return results; -}; - -Sizzle.uniqueSort = function( results ) { - if ( sortOrder ) { - hasDuplicate = baseHasDuplicate; - results.sort( sortOrder ); - - if ( hasDuplicate ) { - for ( var i = 1; i < results.length; i++ ) { - if ( results[i] === results[ i - 1 ] ) { - results.splice( i--, 1 ); - } - } - } - } - - return results; -}; - -Sizzle.matches = function( expr, set ) { - return Sizzle( expr, null, null, set ); -}; - -Sizzle.matchesSelector = function( node, expr ) { - return Sizzle( expr, null, null, [node] ).length > 0; -}; - -Sizzle.find = function( expr, context, isXML ) { - var set, i, len, match, type, left; - - if ( !expr ) { - return []; - } - - for ( i = 0, len = Expr.order.length; i < len; i++ ) { - type = Expr.order[i]; - - if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { - left = match[1]; - match.splice( 1, 1 ); - - if ( left.substr( left.length - 1 ) !== "\\" ) { - match[1] = (match[1] || "").replace( rBackslash, "" ); - set = Expr.find[ type ]( match, context, isXML ); - - if ( set != null ) { - expr = expr.replace( Expr.match[ type ], "" ); - break; - } - } - } - } - - if ( !set ) { - set = typeof context.getElementsByTagName !== "undefined" ? - context.getElementsByTagName( "*" ) : - []; - } - - return { set: set, expr: expr }; -}; - -Sizzle.filter = function( expr, set, inplace, not ) { - var match, anyFound, - type, found, item, filter, left, - i, pass, - old = expr, - result = [], - curLoop = set, - isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); - - while ( expr && set.length ) { - for ( type in Expr.filter ) { - if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { - filter = Expr.filter[ type ]; - left = match[1]; - - anyFound = false; - - match.splice(1,1); - - if ( left.substr( left.length - 1 ) === "\\" ) { - continue; - } - - if ( curLoop === result ) { - result = []; - } - - if ( Expr.preFilter[ type ] ) { - match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); - - if ( !match ) { - anyFound = found = true; - - } else if ( match === true ) { - continue; - } - } - - if ( match ) { - for ( i = 0; (item = curLoop[i]) != null; i++ ) { - if ( item ) { - found = filter( item, match, i, curLoop ); - pass = not ^ found; - - if ( inplace && found != null ) { - if ( pass ) { - anyFound = true; - - } else { - curLoop[i] = false; - } - - } else if ( pass ) { - result.push( item ); - anyFound = true; - } - } - } - } - - if ( found !== undefined ) { - if ( !inplace ) { - curLoop = result; - } - - expr = expr.replace( Expr.match[ type ], "" ); - - if ( !anyFound ) { - return []; - } - - break; - } - } - } - - // Improper expression - if ( expr === old ) { - if ( anyFound == null ) { - Sizzle.error( expr ); - - } else { - break; - } - } - - old = expr; - } - - return curLoop; -}; - -Sizzle.error = function( msg ) { - throw new Error( "Syntax error, unrecognized expression: " + msg ); -}; - -/** - * Utility function for retreiving the text value of an array of DOM nodes - * @param {Array|Element} elem - */ -var getText = Sizzle.getText = function( elem ) { - var i, node, - nodeType = elem.nodeType, - ret = ""; - - if ( nodeType ) { - if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { - // Use textContent || innerText for elements - if ( typeof elem.textContent === 'string' ) { - return elem.textContent; - } else if ( typeof elem.innerText === 'string' ) { - // Replace IE's carriage returns - return elem.innerText.replace( rReturn, '' ); - } else { - // Traverse it's children - for ( elem = elem.firstChild; elem; elem = elem.nextSibling) { - ret += getText( elem ); - } - } - } else if ( nodeType === 3 || nodeType === 4 ) { - return elem.nodeValue; - } - } else { - - // If no nodeType, this is expected to be an array - for ( i = 0; (node = elem[i]); i++ ) { - // Do not traverse comment nodes - if ( node.nodeType !== 8 ) { - ret += getText( node ); - } - } - } - return ret; -}; - -var Expr = Sizzle.selectors = { - order: [ "ID", "NAME", "TAG" ], - - match: { - ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, - CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, - NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, - ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, - TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, - CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, - POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, - PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ - }, - - leftMatch: {}, - - attrMap: { - "class": "className", - "for": "htmlFor" - }, - - attrHandle: { - href: function( elem ) { - return elem.getAttribute( "href" ); - }, - type: function( elem ) { - return elem.getAttribute( "type" ); - } - }, - - relative: { - "+": function(checkSet, part){ - var isPartStr = typeof part === "string", - isTag = isPartStr && !rNonWord.test( part ), - isPartStrNotTag = isPartStr && !isTag; - - if ( isTag ) { - part = part.toLowerCase(); - } - - for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { - if ( (elem = checkSet[i]) ) { - while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} - - checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? - elem || false : - elem === part; - } - } - - if ( isPartStrNotTag ) { - Sizzle.filter( part, checkSet, true ); - } - }, - - ">": function( checkSet, part ) { - var elem, - isPartStr = typeof part === "string", - i = 0, - l = checkSet.length; - - if ( isPartStr && !rNonWord.test( part ) ) { - part = part.toLowerCase(); - - for ( ; i < l; i++ ) { - elem = checkSet[i]; - - if ( elem ) { - var parent = elem.parentNode; - checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; - } - } - - } else { - for ( ; i < l; i++ ) { - elem = checkSet[i]; - - if ( elem ) { - checkSet[i] = isPartStr ? - elem.parentNode : - elem.parentNode === part; - } - } - - if ( isPartStr ) { - Sizzle.filter( part, checkSet, true ); - } - } - }, - - "": function(checkSet, part, isXML){ - var nodeCheck, - doneName = done++, - checkFn = dirCheck; - - if ( typeof part === "string" && !rNonWord.test( part ) ) { - part = part.toLowerCase(); - nodeCheck = part; - checkFn = dirNodeCheck; - } - - checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); - }, - - "~": function( checkSet, part, isXML ) { - var nodeCheck, - doneName = done++, - checkFn = dirCheck; - - if ( typeof part === "string" && !rNonWord.test( part ) ) { - part = part.toLowerCase(); - nodeCheck = part; - checkFn = dirNodeCheck; - } - - checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); - } - }, - - find: { - ID: function( match, context, isXML ) { - if ( typeof context.getElementById !== "undefined" && !isXML ) { - var m = context.getElementById(match[1]); - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - return m && m.parentNode ? [m] : []; - } - }, - - NAME: function( match, context ) { - if ( typeof context.getElementsByName !== "undefined" ) { - var ret = [], - results = context.getElementsByName( match[1] ); - - for ( var i = 0, l = results.length; i < l; i++ ) { - if ( results[i].getAttribute("name") === match[1] ) { - ret.push( results[i] ); - } - } - - return ret.length === 0 ? null : ret; - } - }, - - TAG: function( match, context ) { - if ( typeof context.getElementsByTagName !== "undefined" ) { - return context.getElementsByTagName( match[1] ); - } - } - }, - preFilter: { - CLASS: function( match, curLoop, inplace, result, not, isXML ) { - match = " " + match[1].replace( rBackslash, "" ) + " "; - - if ( isXML ) { - return match; - } - - for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { - if ( elem ) { - if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { - if ( !inplace ) { - result.push( elem ); - } - - } else if ( inplace ) { - curLoop[i] = false; - } - } - } - - return false; - }, - - ID: function( match ) { - return match[1].replace( rBackslash, "" ); - }, - - TAG: function( match, curLoop ) { - return match[1].replace( rBackslash, "" ).toLowerCase(); - }, - - CHILD: function( match ) { - if ( match[1] === "nth" ) { - if ( !match[2] ) { - Sizzle.error( match[0] ); - } - - match[2] = match[2].replace(/^\+|\s*/g, ''); - - // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' - var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( - match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || - !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); - - // calculate the numbers (first)n+(last) including if they are negative - match[2] = (test[1] + (test[2] || 1)) - 0; - match[3] = test[3] - 0; - } - else if ( match[2] ) { - Sizzle.error( match[0] ); - } - - // TODO: Move to normal caching system - match[0] = done++; - - return match; - }, - - ATTR: function( match, curLoop, inplace, result, not, isXML ) { - var name = match[1] = match[1].replace( rBackslash, "" ); - - if ( !isXML && Expr.attrMap[name] ) { - match[1] = Expr.attrMap[name]; - } - - // Handle if an un-quoted value was used - match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); - - if ( match[2] === "~=" ) { - match[4] = " " + match[4] + " "; - } - - return match; - }, - - PSEUDO: function( match, curLoop, inplace, result, not ) { - if ( match[1] === "not" ) { - // If we're dealing with a complex expression, or a simple one - if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { - match[3] = Sizzle(match[3], null, null, curLoop); - - } else { - var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); - - if ( !inplace ) { - result.push.apply( result, ret ); - } - - return false; - } - - } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { - return true; - } - - return match; - }, - - POS: function( match ) { - match.unshift( true ); - - return match; - } - }, - - filters: { - enabled: function( elem ) { - return elem.disabled === false && elem.type !== "hidden"; - }, - - disabled: function( elem ) { - return elem.disabled === true; - }, - - checked: function( elem ) { - return elem.checked === true; - }, - - selected: function( elem ) { - // Accessing this property makes selected-by-default - // options in Safari work properly - if ( elem.parentNode ) { - elem.parentNode.selectedIndex; - } - - return elem.selected === true; - }, - - parent: function( elem ) { - return !!elem.firstChild; - }, - - empty: function( elem ) { - return !elem.firstChild; - }, - - has: function( elem, i, match ) { - return !!Sizzle( match[3], elem ).length; - }, - - header: function( elem ) { - return (/h\d/i).test( elem.nodeName ); - }, - - text: function( elem ) { - var attr = elem.getAttribute( "type" ), type = elem.type; - // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) - // use getAttribute instead to test this case - return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null ); - }, - - radio: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; - }, - - checkbox: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; - }, - - file: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; - }, - - password: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; - }, - - submit: function( elem ) { - var name = elem.nodeName.toLowerCase(); - return (name === "input" || name === "button") && "submit" === elem.type; - }, - - image: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; - }, - - reset: function( elem ) { - var name = elem.nodeName.toLowerCase(); - return (name === "input" || name === "button") && "reset" === elem.type; - }, - - button: function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && "button" === elem.type || name === "button"; - }, - - input: function( elem ) { - return (/input|select|textarea|button/i).test( elem.nodeName ); - }, - - focus: function( elem ) { - return elem === elem.ownerDocument.activeElement; - } - }, - setFilters: { - first: function( elem, i ) { - return i === 0; - }, - - last: function( elem, i, match, array ) { - return i === array.length - 1; - }, - - even: function( elem, i ) { - return i % 2 === 0; - }, - - odd: function( elem, i ) { - return i % 2 === 1; - }, - - lt: function( elem, i, match ) { - return i < match[3] - 0; - }, - - gt: function( elem, i, match ) { - return i > match[3] - 0; - }, - - nth: function( elem, i, match ) { - return match[3] - 0 === i; - }, - - eq: function( elem, i, match ) { - return match[3] - 0 === i; - } - }, - filter: { - PSEUDO: function( elem, match, i, array ) { - var name = match[1], - filter = Expr.filters[ name ]; - - if ( filter ) { - return filter( elem, i, match, array ); - - } else if ( name === "contains" ) { - return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0; - - } else if ( name === "not" ) { - var not = match[3]; - - for ( var j = 0, l = not.length; j < l; j++ ) { - if ( not[j] === elem ) { - return false; - } - } - - return true; - - } else { - Sizzle.error( name ); - } - }, - - CHILD: function( elem, match ) { - var first, last, - doneName, parent, cache, - count, diff, - type = match[1], - node = elem; - - switch ( type ) { - case "only": - case "first": - while ( (node = node.previousSibling) ) { - if ( node.nodeType === 1 ) { - return false; - } - } - - if ( type === "first" ) { - return true; - } - - node = elem; - - /* falls through */ - case "last": - while ( (node = node.nextSibling) ) { - if ( node.nodeType === 1 ) { - return false; - } - } - - return true; - - case "nth": - first = match[2]; - last = match[3]; - - if ( first === 1 && last === 0 ) { - return true; - } - - doneName = match[0]; - parent = elem.parentNode; - - if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) { - count = 0; - - for ( node = parent.firstChild; node; node = node.nextSibling ) { - if ( node.nodeType === 1 ) { - node.nodeIndex = ++count; - } - } - - parent[ expando ] = doneName; - } - - diff = elem.nodeIndex - last; - - if ( first === 0 ) { - return diff === 0; - - } else { - return ( diff % first === 0 && diff / first >= 0 ); - } - } - }, - - ID: function( elem, match ) { - return elem.nodeType === 1 && elem.getAttribute("id") === match; - }, - - TAG: function( elem, match ) { - return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match; - }, - - CLASS: function( elem, match ) { - return (" " + (elem.className || elem.getAttribute("class")) + " ") - .indexOf( match ) > -1; - }, - - ATTR: function( elem, match ) { - var name = match[1], - result = Sizzle.attr ? - Sizzle.attr( elem, name ) : - Expr.attrHandle[ name ] ? - Expr.attrHandle[ name ]( elem ) : - elem[ name ] != null ? - elem[ name ] : - elem.getAttribute( name ), - value = result + "", - type = match[2], - check = match[4]; - - return result == null ? - type === "!=" : - !type && Sizzle.attr ? - result != null : - type === "=" ? - value === check : - type === "*=" ? - value.indexOf(check) >= 0 : - type === "~=" ? - (" " + value + " ").indexOf(check) >= 0 : - !check ? - value && result !== false : - type === "!=" ? - value !== check : - type === "^=" ? - value.indexOf(check) === 0 : - type === "$=" ? - value.substr(value.length - check.length) === check : - type === "|=" ? - value === check || value.substr(0, check.length + 1) === check + "-" : - false; - }, - - POS: function( elem, match, i, array ) { - var name = match[2], - filter = Expr.setFilters[ name ]; - - if ( filter ) { - return filter( elem, i, match, array ); - } - } - } -}; - -var origPOS = Expr.match.POS, - fescape = function(all, num){ - return "\\" + (num - 0 + 1); - }; - -for ( var type in Expr.match ) { - Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); - Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); -} -// Expose origPOS -// "global" as in regardless of relation to brackets/parens -Expr.match.globalPOS = origPOS; - -var makeArray = function( array, results ) { - array = Array.prototype.slice.call( array, 0 ); - - if ( results ) { - results.push.apply( results, array ); - return results; - } - - return array; -}; - -// Perform a simple check to determine if the browser is capable of -// converting a NodeList to an array using builtin methods. -// Also verifies that the returned array holds DOM nodes -// (which is not the case in the Blackberry browser) -try { - Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; - -// Provide a fallback method if it does not work -} catch( e ) { - makeArray = function( array, results ) { - var i = 0, - ret = results || []; - - if ( toString.call(array) === "[object Array]" ) { - Array.prototype.push.apply( ret, array ); - - } else { - if ( typeof array.length === "number" ) { - for ( var l = array.length; i < l; i++ ) { - ret.push( array[i] ); - } - - } else { - for ( ; array[i]; i++ ) { - ret.push( array[i] ); - } - } - } - - return ret; - }; -} - -var sortOrder, siblingCheck; - -if ( document.documentElement.compareDocumentPosition ) { - sortOrder = function( a, b ) { - if ( a === b ) { - hasDuplicate = true; - return 0; - } - - if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { - return a.compareDocumentPosition ? -1 : 1; - } - - return a.compareDocumentPosition(b) & 4 ? -1 : 1; - }; - -} else { - sortOrder = function( a, b ) { - // The nodes are identical, we can exit early - if ( a === b ) { - hasDuplicate = true; - return 0; - - // Fallback to using sourceIndex (in IE) if it's available on both nodes - } else if ( a.sourceIndex && b.sourceIndex ) { - return a.sourceIndex - b.sourceIndex; - } - - var al, bl, - ap = [], - bp = [], - aup = a.parentNode, - bup = b.parentNode, - cur = aup; - - // If the nodes are siblings (or identical) we can do a quick check - if ( aup === bup ) { - return siblingCheck( a, b ); - - // If no parents were found then the nodes are disconnected - } else if ( !aup ) { - return -1; - - } else if ( !bup ) { - return 1; - } - - // Otherwise they're somewhere else in the tree so we need - // to build up a full list of the parentNodes for comparison - while ( cur ) { - ap.unshift( cur ); - cur = cur.parentNode; - } - - cur = bup; - - while ( cur ) { - bp.unshift( cur ); - cur = cur.parentNode; - } - - al = ap.length; - bl = bp.length; - - // Start walking down the tree looking for a discrepancy - for ( var i = 0; i < al && i < bl; i++ ) { - if ( ap[i] !== bp[i] ) { - return siblingCheck( ap[i], bp[i] ); - } - } - - // We ended someplace up the tree so do a sibling check - return i === al ? - siblingCheck( a, bp[i], -1 ) : - siblingCheck( ap[i], b, 1 ); - }; - - siblingCheck = function( a, b, ret ) { - if ( a === b ) { - return ret; - } - - var cur = a.nextSibling; - - while ( cur ) { - if ( cur === b ) { - return -1; - } - - cur = cur.nextSibling; - } - - return 1; - }; -} - -// Check to see if the browser returns elements by name when -// querying by getElementById (and provide a workaround) -(function(){ - // We're going to inject a fake input element with a specified name - var form = document.createElement("div"), - id = "script" + (new Date()).getTime(), - root = document.documentElement; - - form.innerHTML = ""; - - // Inject it into the root element, check its status, and remove it quickly - root.insertBefore( form, root.firstChild ); - - // The workaround has to do additional checks after a getElementById - // Which slows things down for other browsers (hence the branching) - if ( document.getElementById( id ) ) { - Expr.find.ID = function( match, context, isXML ) { - if ( typeof context.getElementById !== "undefined" && !isXML ) { - var m = context.getElementById(match[1]); - - return m ? - m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? - [m] : - undefined : - []; - } - }; - - Expr.filter.ID = function( elem, match ) { - var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); - - return elem.nodeType === 1 && node && node.nodeValue === match; - }; - } - - root.removeChild( form ); - - // release memory in IE - root = form = null; -})(); - -(function(){ - // Check to see if the browser returns only elements - // when doing getElementsByTagName("*") - - // Create a fake element - var div = document.createElement("div"); - div.appendChild( document.createComment("") ); - - // Make sure no comments are found - if ( div.getElementsByTagName("*").length > 0 ) { - Expr.find.TAG = function( match, context ) { - var results = context.getElementsByTagName( match[1] ); - - // Filter out possible comments - if ( match[1] === "*" ) { - var tmp = []; - - for ( var i = 0; results[i]; i++ ) { - if ( results[i].nodeType === 1 ) { - tmp.push( results[i] ); - } - } - - results = tmp; - } - - return results; - }; - } - - // Check to see if an attribute returns normalized href attributes - div.innerHTML = ""; - - if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && - div.firstChild.getAttribute("href") !== "#" ) { - - Expr.attrHandle.href = function( elem ) { - return elem.getAttribute( "href", 2 ); - }; - } - - // release memory in IE - div = null; -})(); - -if ( document.querySelectorAll ) { - (function(){ - var oldSizzle = Sizzle, - div = document.createElement("div"), - id = "__sizzle__"; - - div.innerHTML = "

"; - - // Safari can't handle uppercase or unicode characters when - // in quirks mode. - if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { - return; - } - - Sizzle = function( query, context, extra, seed ) { - context = context || document; - - // Only use querySelectorAll on non-XML documents - // (ID selectors don't work in non-HTML documents) - if ( !seed && !Sizzle.isXML(context) ) { - // See if we find a selector to speed up - var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); - - if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { - // Speed-up: Sizzle("TAG") - if ( match[1] ) { - return makeArray( context.getElementsByTagName( query ), extra ); - - // Speed-up: Sizzle(".CLASS") - } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { - return makeArray( context.getElementsByClassName( match[2] ), extra ); - } - } - - if ( context.nodeType === 9 ) { - // Speed-up: Sizzle("body") - // The body element only exists once, optimize finding it - if ( query === "body" && context.body ) { - return makeArray( [ context.body ], extra ); - - // Speed-up: Sizzle("#ID") - } else if ( match && match[3] ) { - var elem = context.getElementById( match[3] ); - - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - if ( elem && elem.parentNode ) { - // Handle the case where IE and Opera return items - // by name instead of ID - if ( elem.id === match[3] ) { - return makeArray( [ elem ], extra ); - } - - } else { - return makeArray( [], extra ); - } - } - - try { - return makeArray( context.querySelectorAll(query), extra ); - } catch(qsaError) {} - - // qSA works strangely on Element-rooted queries - // We can work around this by specifying an extra ID on the root - // and working up from there (Thanks to Andrew Dupont for the technique) - // IE 8 doesn't work on object elements - } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { - var oldContext = context, - old = context.getAttribute( "id" ), - nid = old || id, - hasParent = context.parentNode, - relativeHierarchySelector = /^\s*[+~]/.test( query ); - - if ( !old ) { - context.setAttribute( "id", nid ); - } else { - nid = nid.replace( /'/g, "\\$&" ); - } - if ( relativeHierarchySelector && hasParent ) { - context = context.parentNode; - } - - try { - if ( !relativeHierarchySelector || hasParent ) { - return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); - } - - } catch(pseudoError) { - } finally { - if ( !old ) { - oldContext.removeAttribute( "id" ); - } - } - } - } - - return oldSizzle(query, context, extra, seed); - }; - - for ( var prop in oldSizzle ) { - Sizzle[ prop ] = oldSizzle[ prop ]; - } - - // release memory in IE - div = null; - })(); -} - -(function(){ - var html = document.documentElement, - matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; - - if ( matches ) { - // Check to see if it's possible to do matchesSelector - // on a disconnected node (IE 9 fails this) - var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), - pseudoWorks = false; - - try { - // This should fail with an exception - // Gecko does not error, returns false instead - matches.call( document.documentElement, "[test!='']:sizzle" ); - - } catch( pseudoError ) { - pseudoWorks = true; - } - - Sizzle.matchesSelector = function( node, expr ) { - // Make sure that attribute selectors are quoted - expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); - - if ( !Sizzle.isXML( node ) ) { - try { - if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { - var ret = matches.call( node, expr ); - - // IE 9's matchesSelector returns false on disconnected nodes - if ( ret || !disconnectedMatch || - // As well, disconnected nodes are said to be in a document - // fragment in IE 9, so check for that - node.document && node.document.nodeType !== 11 ) { - return ret; - } - } - } catch(e) {} - } - - return Sizzle(expr, null, null, [node]).length > 0; - }; - } -})(); - -(function(){ - var div = document.createElement("div"); - - div.innerHTML = "
"; - - // Opera can't find a second classname (in 9.6) - // Also, make sure that getElementsByClassName actually exists - if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { - return; - } - - // Safari caches class attributes, doesn't catch changes (in 3.2) - div.lastChild.className = "e"; - - if ( div.getElementsByClassName("e").length === 1 ) { - return; - } - - Expr.order.splice(1, 0, "CLASS"); - Expr.find.CLASS = function( match, context, isXML ) { - if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { - return context.getElementsByClassName(match[1]); - } - }; - - // release memory in IE - div = null; -})(); - -function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { - for ( var i = 0, l = checkSet.length; i < l; i++ ) { - var elem = checkSet[i]; - - if ( elem ) { - var match = false; - - elem = elem[dir]; - - while ( elem ) { - if ( elem[ expando ] === doneName ) { - match = checkSet[elem.sizset]; - break; - } - - if ( elem.nodeType === 1 && !isXML ){ - elem[ expando ] = doneName; - elem.sizset = i; - } - - if ( elem.nodeName.toLowerCase() === cur ) { - match = elem; - break; - } - - elem = elem[dir]; - } - - checkSet[i] = match; - } - } -} - -function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { - for ( var i = 0, l = checkSet.length; i < l; i++ ) { - var elem = checkSet[i]; - - if ( elem ) { - var match = false; - - elem = elem[dir]; - - while ( elem ) { - if ( elem[ expando ] === doneName ) { - match = checkSet[elem.sizset]; - break; - } - - if ( elem.nodeType === 1 ) { - if ( !isXML ) { - elem[ expando ] = doneName; - elem.sizset = i; - } - - if ( typeof cur !== "string" ) { - if ( elem === cur ) { - match = true; - break; - } - - } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { - match = elem; - break; - } - } - - elem = elem[dir]; - } - - checkSet[i] = match; - } - } -} - -if ( document.documentElement.contains ) { - Sizzle.contains = function( a, b ) { - return a !== b && (a.contains ? a.contains(b) : true); - }; - -} else if ( document.documentElement.compareDocumentPosition ) { - Sizzle.contains = function( a, b ) { - return !!(a.compareDocumentPosition(b) & 16); - }; - -} else { - Sizzle.contains = function() { - return false; - }; -} - -Sizzle.isXML = function( elem ) { - // documentElement is verified for cases where it doesn't yet exist - // (such as loading iframes in IE - #4833) - var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; - - return documentElement ? documentElement.nodeName !== "HTML" : false; -}; - -var posProcess = function( selector, context, seed ) { - var match, - tmpSet = [], - later = "", - root = context.nodeType ? [context] : context; - - // Position selectors must be done after the filter - // And so must :not(positional) so we move all PSEUDOs to the end - while ( (match = Expr.match.PSEUDO.exec( selector )) ) { - later += match[0]; - selector = selector.replace( Expr.match.PSEUDO, "" ); - } - - selector = Expr.relative[selector] ? selector + "*" : selector; - - for ( var i = 0, l = root.length; i < l; i++ ) { - Sizzle( selector, root[i], tmpSet, seed ); - } - - return Sizzle.filter( later, tmpSet ); -}; - -// EXPOSE -// Override sizzle attribute retrieval -Sizzle.attr = jQuery.attr; -Sizzle.selectors.attrMap = {}; -jQuery.find = Sizzle; -jQuery.expr = Sizzle.selectors; -jQuery.expr[":"] = jQuery.expr.filters; -jQuery.unique = Sizzle.uniqueSort; -jQuery.text = Sizzle.getText; -jQuery.isXMLDoc = Sizzle.isXML; -jQuery.contains = Sizzle.contains; - - -})(); - - -var runtil = /Until$/, - rparentsprev = /^(?:parents|prevUntil|prevAll)/, - // Note: This RegExp should be improved, or likely pulled from Sizzle - rmultiselector = /,/, - isSimple = /^.[^:#\[\.,]*$/, - slice = Array.prototype.slice, - POS = jQuery.expr.match.globalPOS, - // methods guaranteed to produce a unique set when starting from a unique set - guaranteedUnique = { - children: true, - contents: true, - next: true, - prev: true - }; - -jQuery.fn.extend({ - find: function( selector ) { - var self = this, - i, l; - - if ( typeof selector !== "string" ) { - return jQuery( selector ).filter(function() { - for ( i = 0, l = self.length; i < l; i++ ) { - if ( jQuery.contains( self[ i ], this ) ) { - return true; - } - } - }); - } - - var ret = this.pushStack( "", "find", selector ), - length, n, r; - - for ( i = 0, l = this.length; i < l; i++ ) { - length = ret.length; - jQuery.find( selector, this[i], ret ); - - if ( i > 0 ) { - // Make sure that the results are unique - for ( n = length; n < ret.length; n++ ) { - for ( r = 0; r < length; r++ ) { - if ( ret[r] === ret[n] ) { - ret.splice(n--, 1); - break; - } - } - } - } - } - - return ret; - }, - - has: function( target ) { - var targets = jQuery( target ); - return this.filter(function() { - for ( var i = 0, l = targets.length; i < l; i++ ) { - if ( jQuery.contains( this, targets[i] ) ) { - return true; - } - } - }); - }, - - not: function( selector ) { - return this.pushStack( winnow(this, selector, false), "not", selector); - }, - - filter: function( selector ) { - return this.pushStack( winnow(this, selector, true), "filter", selector ); - }, - - is: function( selector ) { - return !!selector && ( - typeof selector === "string" ? - // If this is a positional selector, check membership in the returned set - // so $("p:first").is("p:last") won't return true for a doc with two "p". - POS.test( selector ) ? - jQuery( selector, this.context ).index( this[0] ) >= 0 : - jQuery.filter( selector, this ).length > 0 : - this.filter( selector ).length > 0 ); - }, - - closest: function( selectors, context ) { - var ret = [], i, l, cur = this[0]; - - // Array (deprecated as of jQuery 1.7) - if ( jQuery.isArray( selectors ) ) { - var level = 1; - - while ( cur && cur.ownerDocument && cur !== context ) { - for ( i = 0; i < selectors.length; i++ ) { - - if ( jQuery( cur ).is( selectors[ i ] ) ) { - ret.push({ selector: selectors[ i ], elem: cur, level: level }); - } - } - - cur = cur.parentNode; - level++; - } - - return ret; - } - - // String - var pos = POS.test( selectors ) || typeof selectors !== "string" ? - jQuery( selectors, context || this.context ) : - 0; - - for ( i = 0, l = this.length; i < l; i++ ) { - cur = this[i]; - - while ( cur ) { - if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { - ret.push( cur ); - break; - - } else { - cur = cur.parentNode; - if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) { - break; - } - } - } - } - - ret = ret.length > 1 ? jQuery.unique( ret ) : ret; - - return this.pushStack( ret, "closest", selectors ); - }, - - // Determine the position of an element within - // the matched set of elements - index: function( elem ) { - - // No argument, return index in parent - if ( !elem ) { - return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; - } - - // index in selector - if ( typeof elem === "string" ) { - return jQuery.inArray( this[0], jQuery( elem ) ); - } - - // Locate the position of the desired element - return jQuery.inArray( - // If it receives a jQuery object, the first element is used - elem.jquery ? elem[0] : elem, this ); - }, - - add: function( selector, context ) { - var set = typeof selector === "string" ? - jQuery( selector, context ) : - jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), - all = jQuery.merge( this.get(), set ); - - return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? - all : - jQuery.unique( all ) ); - }, - - andSelf: function() { - return this.add( this.prevObject ); - } -}); - -// A painfully simple check to see if an element is disconnected -// from a document (should be improved, where feasible). -function isDisconnected( node ) { - return !node || !node.parentNode || node.parentNode.nodeType === 11; -} - -jQuery.each({ - parent: function( elem ) { - var parent = elem.parentNode; - return parent && parent.nodeType !== 11 ? parent : null; - }, - parents: function( elem ) { - return jQuery.dir( elem, "parentNode" ); - }, - parentsUntil: function( elem, i, until ) { - return jQuery.dir( elem, "parentNode", until ); - }, - next: function( elem ) { - return jQuery.nth( elem, 2, "nextSibling" ); - }, - prev: function( elem ) { - return jQuery.nth( elem, 2, "previousSibling" ); - }, - nextAll: function( elem ) { - return jQuery.dir( elem, "nextSibling" ); - }, - prevAll: function( elem ) { - return jQuery.dir( elem, "previousSibling" ); - }, - nextUntil: function( elem, i, until ) { - return jQuery.dir( elem, "nextSibling", until ); - }, - prevUntil: function( elem, i, until ) { - return jQuery.dir( elem, "previousSibling", until ); - }, - siblings: function( elem ) { - return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); - }, - children: function( elem ) { - return jQuery.sibling( elem.firstChild ); - }, - contents: function( elem ) { - return jQuery.nodeName( elem, "iframe" ) ? - elem.contentDocument || elem.contentWindow.document : - jQuery.makeArray( elem.childNodes ); - } -}, function( name, fn ) { - jQuery.fn[ name ] = function( until, selector ) { - var ret = jQuery.map( this, fn, until ); - - if ( !runtil.test( name ) ) { - selector = until; - } - - if ( selector && typeof selector === "string" ) { - ret = jQuery.filter( selector, ret ); - } - - ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; - - if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { - ret = ret.reverse(); - } - - return this.pushStack( ret, name, slice.call( arguments ).join(",") ); - }; -}); - -jQuery.extend({ - filter: function( expr, elems, not ) { - if ( not ) { - expr = ":not(" + expr + ")"; - } - - return elems.length === 1 ? - jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : - jQuery.find.matches(expr, elems); - }, - - dir: function( elem, dir, until ) { - var matched = [], - cur = elem[ dir ]; - - while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { - if ( cur.nodeType === 1 ) { - matched.push( cur ); - } - cur = cur[dir]; - } - return matched; - }, - - nth: function( cur, result, dir, elem ) { - result = result || 1; - var num = 0; - - for ( ; cur; cur = cur[dir] ) { - if ( cur.nodeType === 1 && ++num === result ) { - break; - } - } - - return cur; - }, - - sibling: function( n, elem ) { - var r = []; - - for ( ; n; n = n.nextSibling ) { - if ( n.nodeType === 1 && n !== elem ) { - r.push( n ); - } - } - - return r; - } -}); - -// Implement the identical functionality for filter and not -function winnow( elements, qualifier, keep ) { - - // Can't pass null or undefined to indexOf in Firefox 4 - // Set to 0 to skip string check - qualifier = qualifier || 0; - - if ( jQuery.isFunction( qualifier ) ) { - return jQuery.grep(elements, function( elem, i ) { - var retVal = !!qualifier.call( elem, i, elem ); - return retVal === keep; - }); - - } else if ( qualifier.nodeType ) { - return jQuery.grep(elements, function( elem, i ) { - return ( elem === qualifier ) === keep; - }); - - } else if ( typeof qualifier === "string" ) { - var filtered = jQuery.grep(elements, function( elem ) { - return elem.nodeType === 1; - }); - - if ( isSimple.test( qualifier ) ) { - return jQuery.filter(qualifier, filtered, !keep); - } else { - qualifier = jQuery.filter( qualifier, filtered ); - } - } - - return jQuery.grep(elements, function( elem, i ) { - return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; - }); -} - - - - -function createSafeFragment( document ) { - var list = nodeNames.split( "|" ), - safeFrag = document.createDocumentFragment(); - - if ( safeFrag.createElement ) { - while ( list.length ) { - safeFrag.createElement( - list.pop() - ); - } - } - return safeFrag; -} - -var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + - "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", - rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, - rleadingWhitespace = /^\s+/, - rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, - rtagName = /<([\w:]+)/, - rtbody = /]", "i"), - // checked="checked" or checked - rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, - rscriptType = /\/(java|ecma)script/i, - rcleanScript = /^\s*", "" ], - legend: [ 1, "
", "
" ], - thead: [ 1, "", "
" ], - tr: [ 2, "", "
" ], - td: [ 3, "", "
" ], - col: [ 2, "", "
" ], - area: [ 1, "", "" ], - _default: [ 0, "", "" ] - }, - safeFragment = createSafeFragment( document ); - -wrapMap.optgroup = wrapMap.option; -wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; -wrapMap.th = wrapMap.td; - -// IE can't serialize and