Repository: jashkenas/underscore Branch: master Commit: 9374840c22e3 Files: 378 Total size: 5.7 MB Directory structure: gitextract_fa8odh1q/ ├── .editorconfig ├── .eslintrc ├── .github/ │ ├── FUNDING.yml │ ├── config/ │ │ └── codeql.yml │ └── workflows/ │ └── codeql-analysis.yml ├── .gitignore ├── .travis.yml ├── CNAME ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── SECURITY.md ├── bower.json ├── docs/ │ ├── .eslintrc │ ├── docco.css │ ├── linked-esm.jst │ ├── main.js │ ├── modules/ │ │ ├── _baseCreate.html │ │ ├── _baseIteratee.html │ │ ├── _cb.html │ │ ├── _chainResult.html │ │ ├── _collectNonEnumProps.html │ │ ├── _createAssigner.html │ │ ├── _createEscaper.html │ │ ├── _createIndexFinder.html │ │ ├── _createPredicateIndexFinder.html │ │ ├── _createReduce.html │ │ ├── _createSizePropertyCheck.html │ │ ├── _deepGet.html │ │ ├── _escapeMap.html │ │ ├── _executeBound.html │ │ ├── _flatten.html │ │ ├── _getByteLength.html │ │ ├── _getLength.html │ │ ├── _group.html │ │ ├── _has.html │ │ ├── _hasObjectTag.html │ │ ├── _isArrayLike.html │ │ ├── _isBufferLike.html │ │ ├── _keyInObj.html │ │ ├── _methodFingerprint.html │ │ ├── _optimizeCb.html │ │ ├── _setup.html │ │ ├── _shallowProperty.html │ │ ├── _stringTagBug.html │ │ ├── _tagTester.html │ │ ├── _toBufferView.html │ │ ├── _toPath.html │ │ ├── _unescapeMap.html │ │ ├── after.html │ │ ├── allKeys.html │ │ ├── before.html │ │ ├── bind.html │ │ ├── bindAll.html │ │ ├── chain.html │ │ ├── chunk.html │ │ ├── clone.html │ │ ├── compact.html │ │ ├── compose.html │ │ ├── constant.html │ │ ├── contains.html │ │ ├── countBy.html │ │ ├── create.html │ │ ├── debounce.html │ │ ├── defaults.html │ │ ├── defer.html │ │ ├── delay.html │ │ ├── difference.html │ │ ├── each.html │ │ ├── escape.html │ │ ├── every.html │ │ ├── extend.html │ │ ├── extendOwn.html │ │ ├── filter.html │ │ ├── find.html │ │ ├── findIndex.html │ │ ├── findKey.html │ │ ├── findLastIndex.html │ │ ├── findWhere.html │ │ ├── first.html │ │ ├── flatten.html │ │ ├── functions.html │ │ ├── get.html │ │ ├── groupBy.html │ │ ├── has.html │ │ ├── identity.html │ │ ├── index-all.html │ │ ├── index-default.html │ │ ├── index.html │ │ ├── indexBy.html │ │ ├── indexOf.html │ │ ├── initial.html │ │ ├── intersection.html │ │ ├── invert.html │ │ ├── invoke.html │ │ ├── isArguments.html │ │ ├── isArray.html │ │ ├── isArrayBuffer.html │ │ ├── isBoolean.html │ │ ├── isDataView.html │ │ ├── isDate.html │ │ ├── isElement.html │ │ ├── isEmpty.html │ │ ├── isEqual.html │ │ ├── isError.html │ │ ├── isFinite.html │ │ ├── isFunction.html │ │ ├── isMap.html │ │ ├── isMatch.html │ │ ├── isNaN.html │ │ ├── isNull.html │ │ ├── isNumber.html │ │ ├── isObject.html │ │ ├── isRegExp.html │ │ ├── isSet.html │ │ ├── isString.html │ │ ├── isSymbol.html │ │ ├── isTypedArray.html │ │ ├── isUndefined.html │ │ ├── isWeakMap.html │ │ ├── isWeakSet.html │ │ ├── iteratee.html │ │ ├── keys.html │ │ ├── last.html │ │ ├── lastIndexOf.html │ │ ├── map.html │ │ ├── mapObject.html │ │ ├── matcher.html │ │ ├── max.html │ │ ├── memoize.html │ │ ├── min.html │ │ ├── mixin.html │ │ ├── negate.html │ │ ├── noop.html │ │ ├── now.html │ │ ├── object.html │ │ ├── omit.html │ │ ├── once.html │ │ ├── pairs.html │ │ ├── partial.html │ │ ├── partition.html │ │ ├── pick.html │ │ ├── pluck.html │ │ ├── property.html │ │ ├── propertyOf.html │ │ ├── random.html │ │ ├── range.html │ │ ├── reduce.html │ │ ├── reduceRight.html │ │ ├── reject.html │ │ ├── rest.html │ │ ├── restArguments.html │ │ ├── result.html │ │ ├── sample.html │ │ ├── shuffle.html │ │ ├── size.html │ │ ├── some.html │ │ ├── sortBy.html │ │ ├── sortedIndex.html │ │ ├── tap.html │ │ ├── template.html │ │ ├── templateSettings.html │ │ ├── throttle.html │ │ ├── times.html │ │ ├── toArray.html │ │ ├── toPath.html │ │ ├── underscore-array-methods.html │ │ ├── underscore.html │ │ ├── unescape.html │ │ ├── union.html │ │ ├── uniq.html │ │ ├── uniqueId.html │ │ ├── unzip.html │ │ ├── values.html │ │ ├── where.html │ │ ├── without.html │ │ ├── wrap.html │ │ └── zip.html │ ├── public/ │ │ └── stylesheets/ │ │ └── normalize.css │ └── underscore-esm.html ├── index.html ├── karma.conf-sauce.js ├── karma.conf.js ├── modules/ │ ├── .eslintrc │ ├── _baseCreate.js │ ├── _baseIteratee.js │ ├── _cb.js │ ├── _chainResult.js │ ├── _collectNonEnumProps.js │ ├── _createAssigner.js │ ├── _createEscaper.js │ ├── _createIndexFinder.js │ ├── _createPredicateIndexFinder.js │ ├── _createReduce.js │ ├── _createSizePropertyCheck.js │ ├── _deepGet.js │ ├── _escapeMap.js │ ├── _executeBound.js │ ├── _flatten.js │ ├── _getByteLength.js │ ├── _getLength.js │ ├── _group.js │ ├── _has.js │ ├── _hasObjectTag.js │ ├── _isArrayLike.js │ ├── _isBufferLike.js │ ├── _keyInObj.js │ ├── _methodFingerprint.js │ ├── _optimizeCb.js │ ├── _setup.js │ ├── _shallowProperty.js │ ├── _stringTagBug.js │ ├── _tagTester.js │ ├── _toBufferView.js │ ├── _toPath.js │ ├── _unescapeMap.js │ ├── after.js │ ├── allKeys.js │ ├── before.js │ ├── bind.js │ ├── bindAll.js │ ├── chain.js │ ├── chunk.js │ ├── clone.js │ ├── compact.js │ ├── compose.js │ ├── constant.js │ ├── contains.js │ ├── countBy.js │ ├── create.js │ ├── debounce.js │ ├── defaults.js │ ├── defer.js │ ├── delay.js │ ├── difference.js │ ├── each.js │ ├── escape.js │ ├── every.js │ ├── extend.js │ ├── extendOwn.js │ ├── filter.js │ ├── find.js │ ├── findIndex.js │ ├── findKey.js │ ├── findLastIndex.js │ ├── findWhere.js │ ├── first.js │ ├── flatten.js │ ├── functions.js │ ├── get.js │ ├── groupBy.js │ ├── has.js │ ├── identity.js │ ├── index-all.js │ ├── index-default.js │ ├── index.js │ ├── indexBy.js │ ├── indexOf.js │ ├── initial.js │ ├── intersection.js │ ├── invert.js │ ├── invoke.js │ ├── isArguments.js │ ├── isArray.js │ ├── isArrayBuffer.js │ ├── isBoolean.js │ ├── isDataView.js │ ├── isDate.js │ ├── isElement.js │ ├── isEmpty.js │ ├── isEqual.js │ ├── isError.js │ ├── isFinite.js │ ├── isFunction.js │ ├── isMap.js │ ├── isMatch.js │ ├── isNaN.js │ ├── isNull.js │ ├── isNumber.js │ ├── isObject.js │ ├── isRegExp.js │ ├── isSet.js │ ├── isString.js │ ├── isSymbol.js │ ├── isTypedArray.js │ ├── isUndefined.js │ ├── isWeakMap.js │ ├── isWeakSet.js │ ├── iteratee.js │ ├── keys.js │ ├── last.js │ ├── lastIndexOf.js │ ├── map.js │ ├── mapObject.js │ ├── matcher.js │ ├── max.js │ ├── memoize.js │ ├── min.js │ ├── mixin.js │ ├── negate.js │ ├── noop.js │ ├── now.js │ ├── object.js │ ├── omit.js │ ├── once.js │ ├── package.json │ ├── pairs.js │ ├── partial.js │ ├── partition.js │ ├── pick.js │ ├── pluck.js │ ├── property.js │ ├── propertyOf.js │ ├── random.js │ ├── range.js │ ├── reduce.js │ ├── reduceRight.js │ ├── reject.js │ ├── rest.js │ ├── restArguments.js │ ├── result.js │ ├── sample.js │ ├── shuffle.js │ ├── size.js │ ├── some.js │ ├── sortBy.js │ ├── sortedIndex.js │ ├── tap.js │ ├── template.js │ ├── templateSettings.js │ ├── throttle.js │ ├── times.js │ ├── toArray.js │ ├── toPath.js │ ├── underscore-array-methods.js │ ├── underscore.js │ ├── unescape.js │ ├── union.js │ ├── uniq.js │ ├── uniqueId.js │ ├── unzip.js │ ├── values.js │ ├── where.js │ ├── without.js │ ├── wrap.js │ └── zip.js ├── package.json ├── patches/ │ └── docco+0.8.0.patch ├── rollup.common.js ├── rollup.config.js ├── rollup.config2.js ├── test/ │ ├── .eslintrc │ ├── arrays.js │ ├── chaining.js │ ├── collections.js │ ├── cross-document.js │ ├── functions.js │ ├── index.html │ ├── objects.js │ ├── overrides.js │ ├── qunit-setup.js │ ├── treeshake.js │ ├── utility.js │ └── vendor/ │ ├── qunit.css │ └── qunit.js ├── test-treeshake/ │ ├── map.js │ ├── rollup.config.js │ └── template.js ├── underscore-esm-min.js ├── underscore-esm.js ├── underscore-min.js ├── underscore-node-f.cjs ├── underscore-node.cjs ├── underscore-node.mjs ├── underscore-umd-min.js ├── underscore-umd.js └── underscore.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ # EditorConfig helps developers define and maintain consistent # coding styles between different editors and IDEs # editorconfig.org root = true [*] indent_style = space indent_size = 2 charset = utf-8 insert_final_newline = true trim_trailing_whitespace = true [**/package.json] indent_size = 2 ================================================ FILE: .eslintrc ================================================ { "env": { "browser": true, "node": true, "amd": true }, "parserOptions": { "ecmaVersion": 3 } } ================================================ FILE: .github/FUNDING.yml ================================================ tidelift: "npm/underscore" patreon: juliangonggrijp github: [jgonggrijp] ================================================ FILE: .github/config/codeql.yml ================================================ paths: - 'modules/**' - 'test/**' - 'test-treeshake/**' - 'rollup*.js' - 'index.html' ================================================ FILE: .github/workflows/codeql-analysis.yml ================================================ # For most projects, this workflow file will not need changing; you simply need # to commit it to your repository. # # You may wish to alter this file to override the set of languages analyzed, # or to provide custom queries or build logic. # # ******** NOTE ******** # We have attempted to detect the languages in your repository. Please check # the `language` matrix defined below to confirm you have the correct set of # supported CodeQL languages. # name: "CodeQL" on: push: branches: [ master ] pull_request: # The branches below must be a subset of the branches above branches: [ master ] paths: - 'modules/**' - 'test/**' - 'test-treeshake/**' - 'rollup*.js' - 'index.html' schedule: - cron: '16 8 * * 3' jobs: analyze: name: Analyze runs-on: ubuntu-latest permissions: actions: read contents: read security-events: write strategy: fail-fast: false matrix: language: [ 'javascript' ] # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] # Learn more about CodeQL language support at # https://codeql.github.com/docs/codeql-overview/supported-languages-and-frameworks/ steps: - name: Checkout repository uses: actions/checkout@v4 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL uses: github/codeql-action/init@v3 with: languages: ${{ matrix.language }} # If you wish to specify custom queries, you can do so here or in a config file. # By default, queries listed here will override any specified in a config file. # Prefix the list here with "+" to use these queries and those in the config file. # queries: ./path/to/local/query, your-org/your-repo/queries@main config-file: ./.github/config/codeql.yml # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below) - name: Autobuild uses: github/codeql-action/autobuild@v3 # ℹ️ Command-line programs to run using the OS shell. # 📚 https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines # and modify them (or add more) to build your code if your project # uses a compiled language #- run: | # make bootstrap # make release - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v3 ================================================ FILE: .gitignore ================================================ raw node_modules *.log *.idea *.swp nyc_output coverage test-treeshake/*-umd.js amd cjs /underscore-node-*-pre* ================================================ FILE: .travis.yml ================================================ language: node_js sudo: false jobs: include: - node_js: 8 env: - DOWNGRADE=true - EXTRA=false - node_js: 12 env: - DOWNGRADE=false - EXTRA=false - node_js: 16 env: - DOWNGRADE=false - EXTRA=true before_install: - "[ $EXTRA = false ] || npm install -g karma-cli" before_script: - "[ $EXTRA = false ] || npm install karma-sauce-launcher" - "[ $DOWNGRADE = false ] || npm install rollup@1" script: - "[ $EXTRA = false ] || npm run lint" - npm run prepare-tests - "[ $EXTRA = false ] || npm run build-umd" - "[ $EXTRA = false ] || npm run build-esm" - "[ $EXTRA = false ] || npm run doc" - "[ $EXTRA = true ] || npm run test-node" - "[ $EXTRA = false ] || npm run coveralls" - "[ $EXTRA = false ] || npm run test-browser" - "[ $EXTRA = false ] || karma start karma.conf-sauce.js" notifications: email: false env: global: - NPM_CONFIG_PROGRESS="false" - secure: bDZSBQfqr21hCayjcZ20IxrV6+XGhxQPFIfwWqEKLrF93Gu8LLVjZRxXE/mE8I8N4Z5WtDNb4ZHrm/TTzmcPa5MuHgIxEdknQCncobH8oimwc83SHwEPk6okeNKl39VlCjvvnmoe/V/KpnknuYn3Rqghtl/Uv9KLpCwskwjTtcw= - secure: SRECgXuwcZTcD3GVxTS2bYNgRyye4vq6BLrV2PH9FyNenowsKQR2EwlC/dppc1Q8NWMgv79J/R96q9JOFh+mEH9L5dlBb2yhnGH8amVeM/ChAJHT/F8YktKM453uVpz5fR00QcCQDDUOx6Pvx374ID0OKNpWKAkQBWA9mPTsLnE= ================================================ FILE: CNAME ================================================ underscorejs.org ================================================ FILE: CODE_OF_CONDUCT.md ================================================ # Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at jashkenas@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Moderation Edits of another user's comment must be clearly marked with "**edit**", the moderator's username, and a timestamp for each occurrence. The only acceptable reasons for editing another user's comment are: 1. to edit out violations of Our Pledge. These edits must include a rationale. 2. to direct future readers to a relevant point later in the conversation (usually the resolution). These edits must be append-only. Deletion of another user's comment is only acceptable when the comment includes no original value, such as "+1", ":+1:", or "me too". ## Self-Moderation Edits of your own comment after someone has responded must be append-only and clearly marked with "**edit**". Typographical and formatting fixes to your own comment which do not affect its meaning are exempt from this requirement. Deletion of your own comment is only acceptable before any later comments have been posted. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [https://contributor-covenant.org/version/1/4][version] [homepage]: https://contributor-covenant.org [version]: https://contributor-covenant.org/version/1/4/ ================================================ FILE: CONTRIBUTING.md ================================================ ## How to contribute to Underscore.js * This project adheres to a [code of conduct](CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code. * Please do not open an issue to report a security issue. Consult the [security policy](SECURITY.md) on what to do instead. * Before you open an issue or send a pull request, [search](https://github.com/jashkenas/underscore/issues) for previous discussions about the same feature or issue. Add to the earlier ticket if you find one. * If you're proposing a new feature, make sure it isn't already implemented in [Underscore-Contrib](https://github.com/documentcloud/underscore-contrib). * When contributing code, make sure that you edit the source code in the `modules/` directory. Also, run `npm install` before committing any changes to ensure that our commit hooks can do their work. * Before sending a pull request for a feature, be sure to have [tests](https://underscorejs.org/test/). * Use the same coding style as the rest of the [codebase](https://github.com/jashkenas/underscore/blob/master/modules/index.js). * In your pull request, do not add documentation or re-build the minified `underscore-umd-min.js` file. We'll do those things before cutting a new release. ### "Help, cloning fails with `fatal: fsck error in packed object`" This error is caused by zero-padded file modes in the commit history. As fixing this is highly destructive, we suggest ignoring these warnings. The simplest way is to instruct git to do so when cloning. For example, to clone from `jashkenas/underscore`, run the following command: `git clone --config transfer.fsckobjects=false git@github.com:jashkenas/underscore.git`. If cloning from a different user or organization, replace `jashkenas` with their name in the previous command. ================================================ FILE: LICENSE ================================================ Copyright (c) 2009-2022 Jeremy Ashkenas, Julian Gonggrijp, and DocumentCloud and Investigative Reporters & Editors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ __ /\ \ __ __ __ ___ \_\ \ __ _ __ ____ ___ ___ _ __ __ /\_\ ____ /\ \/\ \ /' _ `\ /'_ \ /'__`\/\ __\/ ,__\ / ___\ / __`\/\ __\/'__`\ \/\ \ /',__\ \ \ \_\ \/\ \/\ \/\ \ \ \/\ __/\ \ \//\__, `\/\ \__//\ \ \ \ \ \//\ __/ __ \ \ \/\__, `\ \ \____/\ \_\ \_\ \___,_\ \____\\ \_\\/\____/\ \____\ \____/\ \_\\ \____\/\_\ _\ \ \/\____/ \/___/ \/_/\/_/\/__,_ /\/____/ \/_/ \/___/ \/____/\/___/ \/_/ \/____/\/_//\ \_\ \/___/ \ \____/ \/___/ Underscore.js is a utility-belt library for JavaScript that provides support for the usual functional suspects (each, map, reduce, filter...) without extending any core JavaScript objects. For Docs, License, Tests, and pre-packed downloads, see: https://underscorejs.org For support and questions, please consult our [security policy](SECURITY.md), [the gitter channel](https://gitter.im/jashkenas/underscore) or [stackoverflow](https://stackoverflow.com/search?q=underscore.js) Underscore is an open-sourced component of DocumentCloud: https://github.com/documentcloud Many thanks to our contributors: https://github.com/jashkenas/underscore/contributors You can support the project by donating on [Patreon](https://patreon.com/juliangonggrijp). Enterprise coverage is available as part of the [Tidelift Subscription](https://tidelift.com/subscription/pkg/npm-underscore?utm_source=npm-underscore&utm_medium=referral&utm_campaign=enterprise). This project adheres to a [code of conduct](CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code. ================================================ FILE: SECURITY.md ================================================ # Security Policy ## Supported Versions We currently support the following versions of Underscore with security updates: - the latest commit on the `master` branch (published as "edge" on the [project website][website]); - the 1.x release tagged as [latest][npm-latest] on npm; - any release tagged as [preview][npm-preview] on npm, if present. [website]: https://underscorejs.org [npm-latest]: https://www.npmjs.com/package/underscore/v/latest [npm-preview]: https://www.npmjs.com/package/underscore/v/preview ## Reporting a Vulnerability Please report security issues by sending an email to dev@juliangonggrijp.com and jashkenas@gmail.com. Do __not__ submit an issue ticket or pull request or otherwise publicly disclose the issue. After receiving your email, we will respond as soon as possible and indicate what we plan to do. ## Disclosure policy After confirming a vulnerability, we will generally release a security update as soon as possible, including the minimum amount of information required for software maintainers and system administrators to assess the urgency of the update for their particular situation. We postpone the publication of any further details such as code comments, tests, commit history and diffs, in order to enable a substantial share of the users to install the security fix before this time. Upon publication of full details, we will credit the reporter if the reporter wishes to be publicly identified. ================================================ FILE: bower.json ================================================ { "name": "underscore", "main": "underscore-umd.js", "keywords": ["util", "functional", "server", "client", "browser"], "ignore" : ["docs", "test", "*.yml", "CNAME", "index.html", "favicon.ico", "CONTRIBUTING.md", ".*", "package.json", "karma.*"] } ================================================ FILE: docs/.eslintrc ================================================ { "globals": { "_": true, "parserOptions": {}, "rules": [], } } ================================================ FILE: docs/docco.css ================================================ /*--------------------- Typography ----------------------------*/ @font-face { font-family: 'aller-light'; src: url('public/fonts/aller-light.eot'); src: url('public/fonts/aller-light.eot?#iefix') format('embedded-opentype'), url('public/fonts/aller-light.woff') format('woff'), url('public/fonts/aller-light.ttf') format('truetype'); font-weight: normal; font-style: normal; } @font-face { font-family: 'aller-bold'; src: url('public/fonts/aller-bold.eot'); src: url('public/fonts/aller-bold.eot?#iefix') format('embedded-opentype'), url('public/fonts/aller-bold.woff') format('woff'), url('public/fonts/aller-bold.ttf') format('truetype'); font-weight: normal; font-style: normal; } @font-face { font-family: 'roboto-black'; src: url('public/fonts/roboto-black.eot'); src: url('public/fonts/roboto-black.eot?#iefix') format('embedded-opentype'), url('public/fonts/roboto-black.woff') format('woff'), url('public/fonts/roboto-black.ttf') format('truetype'); font-weight: normal; font-style: normal; } /*--------------------- Layout ----------------------------*/ html { height: 100%; } body { font-family: "aller-light"; font-size: 14px; line-height: 18px; color: #30404f; margin: 0; padding: 0; height:100%; } #container { min-height: 100%; } a { color: #000; } b, strong { font-weight: normal; font-family: "aller-bold"; } p { margin: 15px 0 0px; } .annotation ul, .annotation ol { margin: 25px 0; } .annotation ul li, .annotation ol li { font-size: 14px; line-height: 18px; margin: 10px 0; } h1, h2, h3, h4, h5, h6 { color: #112233; line-height: 1em; font-weight: normal; font-family: "roboto-black"; text-transform: uppercase; margin: 30px 0 15px 0; } h1 { margin-top: 40px; } h2 { font-size: 1.26em; } hr { border: 0; background: 1px #ddd; height: 1px; margin: 20px 0; } pre, tt, code { font-size: 12px; line-height: 16px; font-family: Menlo, Monaco, Consolas, "Lucida Console", monospace; margin: 0; padding: 0; } .annotation pre { display: block; margin: 0; padding: 7px 10px; background: #fcfcfc; -moz-box-shadow: inset 0 0 10px rgba(0,0,0,0.1); -webkit-box-shadow: inset 0 0 10px rgba(0,0,0,0.1); box-shadow: inset 0 0 10px rgba(0,0,0,0.1); overflow-x: auto; } .annotation pre code { border: 0; padding: 0; background: transparent; } blockquote { border-left: 5px solid #ccc; margin: 0; padding: 1px 0 1px 1em; } .sections blockquote p { font-family: Menlo, Consolas, Monaco, monospace; font-size: 12px; line-height: 16px; color: #999; margin: 10px 0 0; white-space: pre-wrap; } ul.sections { list-style: none; padding:0 0 5px 0;; margin:0; } /* Force border-box so that % widths fit the parent container without overlap because of margin/padding. More Info : http://www.quirksmode.org/css/box.html */ ul.sections > li > div { -moz-box-sizing: border-box; /* firefox */ -ms-box-sizing: border-box; /* ie */ -webkit-box-sizing: border-box; /* webkit */ -khtml-box-sizing: border-box; /* konqueror */ box-sizing: border-box; /* css3 */ } /*---------------------- Jump Page -----------------------------*/ #jump_to, #jump_page { margin: 0; background: white; -webkit-box-shadow: 0 0 25px #777; -moz-box-shadow: 0 0 25px #777; -webkit-border-bottom-left-radius: 5px; -moz-border-radius-bottomleft: 5px; font: 16px Arial; cursor: pointer; text-align: right; list-style: none; } #jump_to a { text-decoration: none; } #jump_to a.large { display: none; } #jump_to a.small { font-size: 22px; font-weight: bold; color: #676767; } #jump_to, #jump_wrapper { position: fixed; right: 0; top: 0; padding: 10px 15px; margin:0; } #jump_wrapper { display: none; padding:0; } #jump_to:hover #jump_wrapper { display: block; } #jump_page_wrapper{ position: fixed; right: 0; top: 0; bottom: 0; } #jump_page { padding: 5px 0 3px; margin: 0 0 25px 25px; max-height: 100%; overflow: auto; } #jump_page .source { display: block; padding: 15px; text-decoration: none; border-top: 1px solid #eee; } #jump_page .source:hover { background: #f5f5ff; } #jump_page .source:first-child { } /*---------------------- Low resolutions (> 320px) ---------------------*/ @media only screen and (min-width: 320px) { .pilwrap { display: none; } ul.sections > li > div { display: block; padding:5px 10px 0 10px; } ul.sections > li > div.annotation ul, ul.sections > li > div.annotation ol { padding-left: 30px; } ul.sections > li > div.content { overflow-x:auto; -webkit-box-shadow: inset 0 0 5px #e5e5ee; box-shadow: inset 0 0 5px #e5e5ee; border: 1px solid #dedede; margin:5px 10px 5px 10px; padding-bottom: 5px; } ul.sections > li > div.annotation pre { margin: 7px 0 7px; padding-left: 15px; } ul.sections > li > div.annotation p tt, .annotation code { background: #f8f8ff; border: 1px solid #dedede; font-size: 12px; padding: 0 0.2em; } } /*---------------------- (> 481px) ---------------------*/ @media only screen and (min-width: 481px) { #container { position: relative; } body { background-color: #F5F5FF; font-size: 15px; line-height: 21px; } pre, tt, code { line-height: 18px; } p, ul, ol { margin: 0 0 15px; } #jump_to { padding: 5px 10px; } #jump_wrapper { padding: 0; } #jump_to, #jump_page { font: 10px Arial; text-transform: uppercase; } #jump_page .source { padding: 5px 10px; } #jump_to a.large { display: inline-block; } #jump_to a.small { display: none; } #background { position: absolute; top: 0; bottom: 0; width: 350px; background: #fff; border-right: 1px solid #e5e5ee; z-index: -1; } ul.sections > li > div.annotation ul, ul.sections > li > div.annotation ol { padding-left: 40px; } ul.sections > li { white-space: nowrap; } ul.sections > li > div { display: inline-block; } ul.sections > li > div.annotation { max-width: 350px; min-width: 350px; min-height: 5px; padding: 13px; overflow-x: hidden; white-space: normal; vertical-align: top; text-align: left; } ul.sections > li > div.annotation pre { margin: 15px 0 15px; padding-left: 15px; } ul.sections > li > div.content { padding: 13px; vertical-align: top; border: none; -webkit-box-shadow: none; box-shadow: none; } .pilwrap { position: relative; display: inline; } .pilcrow { font: 12px Arial; text-decoration: none; color: #454545; position: absolute; top: 3px; left: -20px; padding: 1px 2px; opacity: 0; -webkit-transition: opacity 0.2s linear; } .for-h1 .pilcrow { top: 47px; } .for-h2 .pilcrow, .for-h3 .pilcrow, .for-h4 .pilcrow { top: 35px; } ul.sections > li > div.annotation:hover .pilcrow { opacity: 1; } } /*---------------------- (> 1025px) ---------------------*/ @media only screen and (min-width: 1025px) { body { font-size: 16px; line-height: 24px; } #background { width: 525px; } ul.sections > li > div.annotation { max-width: 525px; min-width: 525px; padding: 10px 25px 1px 50px; } ul.sections > li > div.content { padding: 9px 15px 16px 25px; } } /*---------------------- Syntax Highlighting -----------------------------*/ td.linenos { background-color: #f0f0f0; padding-right: 10px; } span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; } /* github.com style (c) Vasily Polovnyov */ pre code { display: block; padding: 0.5em; color: #000; background: #f8f8ff } pre .hljs-comment, pre .hljs-template_comment, pre .hljs-diff .hljs-header, pre .hljs-javadoc { color: #408080; font-style: italic } pre .hljs-keyword, pre .hljs-assignment, pre .hljs-literal, pre .hljs-css .hljs-rule .hljs-keyword, pre .hljs-winutils, pre .hljs-javascript .hljs-title, pre .hljs-lisp .hljs-title, pre .hljs-subst { color: #954121; /*font-weight: bold*/ } pre .hljs-number, pre .hljs-hexcolor { color: #40a070 } pre .hljs-string, pre .hljs-tag .hljs-value, pre .hljs-phpdoc, pre .hljs-tex .hljs-formula { color: #219161; } pre .hljs-title, pre .hljs-id { color: #19469D; } pre .hljs-params { color: #00F; } pre .hljs-javascript .hljs-title, pre .hljs-lisp .hljs-title, pre .hljs-subst { font-weight: normal } pre .hljs-class .hljs-title, pre .hljs-haskell .hljs-label, pre .hljs-tex .hljs-command { color: #458; font-weight: bold } pre .hljs-tag, pre .hljs-tag .hljs-title, pre .hljs-rules .hljs-property, pre .hljs-django .hljs-tag .hljs-keyword { color: #000080; font-weight: normal } pre .hljs-attribute, pre .hljs-variable, pre .hljs-instancevar, pre .hljs-lisp .hljs-body { color: #008080 } pre .hljs-regexp { color: #B68 } pre .hljs-class { color: #458; font-weight: bold } pre .hljs-symbol, pre .hljs-ruby .hljs-symbol .hljs-string, pre .hljs-ruby .hljs-symbol .hljs-keyword, pre .hljs-ruby .hljs-symbol .hljs-keymethods, pre .hljs-lisp .hljs-keyword, pre .hljs-tex .hljs-special, pre .hljs-input_number { color: #990073 } pre .hljs-builtin, pre .hljs-constructor, pre .hljs-built_in, pre .hljs-lisp .hljs-title { color: #0086b3 } pre .hljs-preprocessor, pre .hljs-pi, pre .hljs-doctype, pre .hljs-shebang, pre .hljs-cdata { color: #999; font-weight: bold } pre .hljs-deletion { background: #fdd } pre .hljs-addition { background: #dfd } pre .hljs-diff .hljs-change { background: #0086b3 } pre .hljs-chunk { color: #aaa } pre .hljs-tex .hljs-formula { opacity: 0.5; } ================================================ FILE: docs/linked-esm.jst ================================================ <% /* This is an extended version of the resources/parallel/docco.jst that is bundled with Docco 0.8.0. The license of the original file is available over here: https://github.com/jashkenas/docco/blob/master/LICENSE. The extension adds hyperlinking to javascript import statements. */ %> <%= title %>
<% if (sources.length > 1) { %> <% } %>
<% /* Start of hyperlinking extension */ %> <% /* End of hyperlinking extension */ %> ================================================ FILE: docs/main.js ================================================ (function() { var functions = document.querySelectorAll('[data-name]'); var sections = document.querySelectorAll('.searchable_section'); var searchInput = document.getElementById('function_filter'); function searchValue() { return searchInput.value.trim().replace(/^_\.?/, ''); } function strIn(a, b) { a = a.toLowerCase(); b = b.toLowerCase(); return b.indexOf(a) >= 0; } function doesMatch(element) { var name = element.getAttribute('data-name'); var aliases = element.getAttribute('data-aliases') || ''; var value = searchValue(); return strIn(value, name) || strIn(value, aliases); } function filterElement(element) { element.style.display = doesMatch(element) ? '' : 'none'; } function filterToc() { _.each(functions, filterElement); var emptySearch = searchValue() === ''; // Hide the titles of empty sections _.each(sections, function(section) { var sectionFunctions = section.querySelectorAll('[data-name]'); var showSection = emptySearch || _.some(sectionFunctions, doesMatch); section.style.display = showSection ? '' : 'none'; }); } function gotoFirst() { var firstFunction = _.find(functions, doesMatch); if (firstFunction) { window.location.hash = firstFunction.getAttribute('data-name'); searchInput.focus(); } } searchInput.addEventListener('input', filterToc, false); // Press "Enter" to jump to the first matching function searchInput.addEventListener('keypress', function(e) { if (e.which === 13) { gotoFirst(); } }); // Press "/" to search document.body.addEventListener('keyup', function(event) { if (191 === event.which) { searchInput.focus(); } }); }()); ================================================ FILE: docs/modules/_baseCreate.html ================================================ _baseCreate.js
================================================ FILE: docs/modules/_baseIteratee.html ================================================ _baseIteratee.js
================================================ FILE: docs/modules/_cb.html ================================================ _cb.js
================================================ FILE: docs/modules/_chainResult.html ================================================ _chainResult.js
================================================ FILE: docs/modules/_collectNonEnumProps.html ================================================ _collectNonEnumProps.js
================================================ FILE: docs/modules/_createAssigner.html ================================================ _createAssigner.js
================================================ FILE: docs/modules/_createEscaper.html ================================================ _createEscaper.js
================================================ FILE: docs/modules/_createIndexFinder.html ================================================ _createIndexFinder.js
================================================ FILE: docs/modules/_createPredicateIndexFinder.html ================================================ _createPredicateIndexFinder.js
================================================ FILE: docs/modules/_createReduce.html ================================================ _createReduce.js
================================================ FILE: docs/modules/_createSizePropertyCheck.html ================================================ _createSizePropertyCheck.js
================================================ FILE: docs/modules/_deepGet.html ================================================ _deepGet.js
================================================ FILE: docs/modules/_escapeMap.html ================================================ _escapeMap.js
================================================ FILE: docs/modules/_executeBound.html ================================================ _executeBound.js
================================================ FILE: docs/modules/_flatten.html ================================================ _flatten.js
================================================ FILE: docs/modules/_getByteLength.html ================================================ _getByteLength.js
================================================ FILE: docs/modules/_getLength.html ================================================ _getLength.js
================================================ FILE: docs/modules/_group.html ================================================ _group.js
================================================ FILE: docs/modules/_has.html ================================================ _has.js
================================================ FILE: docs/modules/_hasObjectTag.html ================================================ _hasObjectTag.js
================================================ FILE: docs/modules/_isArrayLike.html ================================================ _isArrayLike.js
================================================ FILE: docs/modules/_isBufferLike.html ================================================ _isBufferLike.js
================================================ FILE: docs/modules/_keyInObj.html ================================================ _keyInObj.js
================================================ FILE: docs/modules/_methodFingerprint.html ================================================ _methodFingerprint.js
================================================ FILE: docs/modules/_optimizeCb.html ================================================ _optimizeCb.js
================================================ FILE: docs/modules/_setup.html ================================================ _setup.js
================================================ FILE: docs/modules/_shallowProperty.html ================================================ _shallowProperty.js
================================================ FILE: docs/modules/_stringTagBug.html ================================================ _stringTagBug.js
================================================ FILE: docs/modules/_tagTester.html ================================================ _tagTester.js
================================================ FILE: docs/modules/_toBufferView.html ================================================ _toBufferView.js
================================================ FILE: docs/modules/_toPath.html ================================================ _toPath.js
================================================ FILE: docs/modules/_unescapeMap.html ================================================ _unescapeMap.js
================================================ FILE: docs/modules/after.html ================================================ after.js
================================================ FILE: docs/modules/allKeys.html ================================================ allKeys.js
================================================ FILE: docs/modules/before.html ================================================ before.js
================================================ FILE: docs/modules/bind.html ================================================ bind.js
================================================ FILE: docs/modules/bindAll.html ================================================ bindAll.js
================================================ FILE: docs/modules/chain.html ================================================ chain.js
================================================ FILE: docs/modules/chunk.html ================================================ chunk.js
================================================ FILE: docs/modules/clone.html ================================================ clone.js
================================================ FILE: docs/modules/compact.html ================================================ compact.js
================================================ FILE: docs/modules/compose.html ================================================ compose.js
================================================ FILE: docs/modules/constant.html ================================================ constant.js
================================================ FILE: docs/modules/contains.html ================================================ contains.js
================================================ FILE: docs/modules/countBy.html ================================================ countBy.js
================================================ FILE: docs/modules/create.html ================================================ create.js
================================================ FILE: docs/modules/debounce.html ================================================ debounce.js
================================================ FILE: docs/modules/defaults.html ================================================ defaults.js
================================================ FILE: docs/modules/defer.html ================================================ defer.js
================================================ FILE: docs/modules/delay.html ================================================ delay.js
================================================ FILE: docs/modules/difference.html ================================================ difference.js
================================================ FILE: docs/modules/each.html ================================================ each.js
================================================ FILE: docs/modules/escape.html ================================================ escape.js
================================================ FILE: docs/modules/every.html ================================================ every.js
================================================ FILE: docs/modules/extend.html ================================================ extend.js
================================================ FILE: docs/modules/extendOwn.html ================================================ extendOwn.js
================================================ FILE: docs/modules/filter.html ================================================ filter.js
================================================ FILE: docs/modules/find.html ================================================ find.js
================================================ FILE: docs/modules/findIndex.html ================================================ findIndex.js
================================================ FILE: docs/modules/findKey.html ================================================ findKey.js
================================================ FILE: docs/modules/findLastIndex.html ================================================ findLastIndex.js
================================================ FILE: docs/modules/findWhere.html ================================================ findWhere.js
================================================ FILE: docs/modules/first.html ================================================ first.js
================================================ FILE: docs/modules/flatten.html ================================================ flatten.js
================================================ FILE: docs/modules/functions.html ================================================ functions.js
================================================ FILE: docs/modules/get.html ================================================ get.js
================================================ FILE: docs/modules/groupBy.html ================================================ groupBy.js
================================================ FILE: docs/modules/has.html ================================================ has.js
================================================ FILE: docs/modules/identity.html ================================================ identity.js
================================================ FILE: docs/modules/index-all.html ================================================ ESM Exports
================================================ FILE: docs/modules/index-default.html ================================================ Default Export
================================================ FILE: docs/modules/index.html ================================================ Named Exports
================================================ FILE: docs/modules/indexBy.html ================================================ indexBy.js
================================================ FILE: docs/modules/indexOf.html ================================================ indexOf.js
================================================ FILE: docs/modules/initial.html ================================================ initial.js
================================================ FILE: docs/modules/intersection.html ================================================ intersection.js
================================================ FILE: docs/modules/invert.html ================================================ invert.js
================================================ FILE: docs/modules/invoke.html ================================================ invoke.js
================================================ FILE: docs/modules/isArguments.html ================================================ isArguments.js
================================================ FILE: docs/modules/isArray.html ================================================ isArray.js
================================================ FILE: docs/modules/isArrayBuffer.html ================================================ isArrayBuffer.js
================================================ FILE: docs/modules/isBoolean.html ================================================ isBoolean.js
================================================ FILE: docs/modules/isDataView.html ================================================ isDataView.js
================================================ FILE: docs/modules/isDate.html ================================================ isDate.js
================================================ FILE: docs/modules/isElement.html ================================================ isElement.js
================================================ FILE: docs/modules/isEmpty.html ================================================ isEmpty.js
================================================ FILE: docs/modules/isEqual.html ================================================ isEqual.js
================================================ FILE: docs/modules/isError.html ================================================ isError.js
================================================ FILE: docs/modules/isFinite.html ================================================ isFinite.js
================================================ FILE: docs/modules/isFunction.html ================================================ isFunction.js
================================================ FILE: docs/modules/isMap.html ================================================ isMap.js
================================================ FILE: docs/modules/isMatch.html ================================================ isMatch.js
================================================ FILE: docs/modules/isNaN.html ================================================ isNaN.js
================================================ FILE: docs/modules/isNull.html ================================================ isNull.js
================================================ FILE: docs/modules/isNumber.html ================================================ isNumber.js
================================================ FILE: docs/modules/isObject.html ================================================ isObject.js
================================================ FILE: docs/modules/isRegExp.html ================================================ isRegExp.js
================================================ FILE: docs/modules/isSet.html ================================================ isSet.js
================================================ FILE: docs/modules/isString.html ================================================ isString.js
================================================ FILE: docs/modules/isSymbol.html ================================================ isSymbol.js
================================================ FILE: docs/modules/isTypedArray.html ================================================ isTypedArray.js
================================================ FILE: docs/modules/isUndefined.html ================================================ isUndefined.js
================================================ FILE: docs/modules/isWeakMap.html ================================================ isWeakMap.js
================================================ FILE: docs/modules/isWeakSet.html ================================================ isWeakSet.js
================================================ FILE: docs/modules/iteratee.html ================================================ iteratee.js
================================================ FILE: docs/modules/keys.html ================================================ keys.js
================================================ FILE: docs/modules/last.html ================================================ last.js
================================================ FILE: docs/modules/lastIndexOf.html ================================================ lastIndexOf.js
================================================ FILE: docs/modules/map.html ================================================ map.js
================================================ FILE: docs/modules/mapObject.html ================================================ mapObject.js
================================================ FILE: docs/modules/matcher.html ================================================ matcher.js
================================================ FILE: docs/modules/max.html ================================================ max.js
================================================ FILE: docs/modules/memoize.html ================================================ memoize.js
================================================ FILE: docs/modules/min.html ================================================ min.js
================================================ FILE: docs/modules/mixin.html ================================================ mixin.js
================================================ FILE: docs/modules/negate.html ================================================ negate.js
================================================ FILE: docs/modules/noop.html ================================================ noop.js
================================================ FILE: docs/modules/now.html ================================================ now.js
================================================ FILE: docs/modules/object.html ================================================ object.js
================================================ FILE: docs/modules/omit.html ================================================ omit.js
================================================ FILE: docs/modules/once.html ================================================ once.js
================================================ FILE: docs/modules/pairs.html ================================================ pairs.js
================================================ FILE: docs/modules/partial.html ================================================ partial.js
================================================ FILE: docs/modules/partition.html ================================================ partition.js
================================================ FILE: docs/modules/pick.html ================================================ pick.js
================================================ FILE: docs/modules/pluck.html ================================================ pluck.js
================================================ FILE: docs/modules/property.html ================================================ property.js
================================================ FILE: docs/modules/propertyOf.html ================================================ propertyOf.js
================================================ FILE: docs/modules/random.html ================================================ random.js
================================================ FILE: docs/modules/range.html ================================================ range.js
================================================ FILE: docs/modules/reduce.html ================================================ reduce.js
================================================ FILE: docs/modules/reduceRight.html ================================================ reduceRight.js
================================================ FILE: docs/modules/reject.html ================================================ reject.js
================================================ FILE: docs/modules/rest.html ================================================ rest.js
================================================ FILE: docs/modules/restArguments.html ================================================ restArguments.js
================================================ FILE: docs/modules/result.html ================================================ result.js
================================================ FILE: docs/modules/sample.html ================================================ sample.js
================================================ FILE: docs/modules/shuffle.html ================================================ shuffle.js
================================================ FILE: docs/modules/size.html ================================================ size.js
================================================ FILE: docs/modules/some.html ================================================ some.js
================================================ FILE: docs/modules/sortBy.html ================================================ sortBy.js
================================================ FILE: docs/modules/sortedIndex.html ================================================ sortedIndex.js
================================================ FILE: docs/modules/tap.html ================================================ tap.js
================================================ FILE: docs/modules/template.html ================================================ template.js
================================================ FILE: docs/modules/templateSettings.html ================================================ templateSettings.js
================================================ FILE: docs/modules/throttle.html ================================================ throttle.js
================================================ FILE: docs/modules/times.html ================================================ times.js
================================================ FILE: docs/modules/toArray.html ================================================ toArray.js
================================================ FILE: docs/modules/toPath.html ================================================ toPath.js
================================================ FILE: docs/modules/underscore-array-methods.html ================================================ underscore-array-methods.js
================================================ FILE: docs/modules/underscore.html ================================================ underscore.js
================================================ FILE: docs/modules/unescape.html ================================================ unescape.js
================================================ FILE: docs/modules/union.html ================================================ union.js
================================================ FILE: docs/modules/uniq.html ================================================ uniq.js
================================================ FILE: docs/modules/uniqueId.html ================================================ uniqueId.js
================================================ FILE: docs/modules/unzip.html ================================================ unzip.js
================================================ FILE: docs/modules/values.html ================================================ values.js
================================================ FILE: docs/modules/where.html ================================================ where.js
================================================ FILE: docs/modules/without.html ================================================ without.js
================================================ FILE: docs/modules/wrap.html ================================================ wrap.js
================================================ FILE: docs/modules/zip.html ================================================ zip.js
================================================ FILE: docs/public/stylesheets/normalize.css ================================================ /*! normalize.css v2.0.1 | MIT License | git.io/normalize */ /* ========================================================================== HTML5 display definitions ========================================================================== */ /* * Corrects `block` display not defined in IE 8/9. */ article, aside, details, figcaption, figure, footer, header, hgroup, nav, section, summary { display: block; } /* * Corrects `inline-block` display not defined in IE 8/9. */ audio, canvas, video { display: inline-block; } /* * Prevents modern browsers from displaying `audio` without controls. * Remove excess height in iOS 5 devices. */ audio:not([controls]) { display: none; height: 0; } /* * Addresses styling for `hidden` attribute not present in IE 8/9. */ [hidden] { display: none; } /* ========================================================================== Base ========================================================================== */ /* * 1. Sets default font family to sans-serif. * 2. Prevents iOS text size adjust after orientation change, without disabling * user zoom. */ html { font-family: sans-serif; /* 1 */ -webkit-text-size-adjust: 100%; /* 2 */ -ms-text-size-adjust: 100%; /* 2 */ } /* * Removes default margin. */ body { margin: 0; } /* ========================================================================== Links ========================================================================== */ /* * Addresses `outline` inconsistency between Chrome and other browsers. */ a:focus { outline: thin dotted; } /* * Improves readability when focused and also mouse hovered in all browsers. */ a:active, a:hover { outline: 0; } /* ========================================================================== Typography ========================================================================== */ /* * Addresses `h1` font sizes within `section` and `article` in Firefox 4+, * Safari 5, and Chrome. */ h1 { font-size: 2em; } /* * Addresses styling not present in IE 8/9, Safari 5, and Chrome. */ abbr[title] { border-bottom: 1px dotted; } /* * Addresses style set to `bolder` in Firefox 4+, Safari 5, and Chrome. */ b, strong { font-weight: bold; } /* * Addresses styling not present in Safari 5 and Chrome. */ dfn { font-style: italic; } /* * Addresses styling not present in IE 8/9. */ mark { background: #ff0; color: #000; } /* * Corrects font family set oddly in Safari 5 and Chrome. */ code, kbd, pre, samp { font-family: monospace, serif; font-size: 1em; } /* * Improves readability of pre-formatted text in all browsers. */ pre { white-space: pre; white-space: pre-wrap; word-wrap: break-word; } /* * Sets consistent quote types. */ q { quotes: "\201C" "\201D" "\2018" "\2019"; } /* * Addresses inconsistent and variable font size in all browsers. */ small { font-size: 80%; } /* * Prevents `sub` and `sup` affecting `line-height` in all browsers. */ sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sup { top: -0.5em; } sub { bottom: -0.25em; } /* ========================================================================== Embedded content ========================================================================== */ /* * Removes border when inside `a` element in IE 8/9. */ img { border: 0; } /* * Corrects overflow displayed oddly in IE 9. */ svg:not(:root) { overflow: hidden; } /* ========================================================================== Figures ========================================================================== */ /* * Addresses margin not present in IE 8/9 and Safari 5. */ figure { margin: 0; } /* ========================================================================== Forms ========================================================================== */ /* * Define consistent border, margin, and padding. */ fieldset { border: 1px solid #c0c0c0; margin: 0 2px; padding: 0.35em 0.625em 0.75em; } /* * 1. Corrects color not being inherited in IE 8/9. * 2. Remove padding so people aren't caught out if they zero out fieldsets. */ legend { border: 0; /* 1 */ padding: 0; /* 2 */ } /* * 1. Corrects font family not being inherited in all browsers. * 2. Corrects font size not being inherited in all browsers. * 3. Addresses margins set differently in Firefox 4+, Safari 5, and Chrome */ button, input, select, textarea { font-family: inherit; /* 1 */ font-size: 100%; /* 2 */ margin: 0; /* 3 */ } /* * Addresses Firefox 4+ setting `line-height` on `input` using `!important` in * the UA stylesheet. */ button, input { line-height: normal; } /* * 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio` * and `video` controls. * 2. Corrects inability to style clickable `input` types in iOS. * 3. Improves usability and consistency of cursor style between image-type * `input` and others. */ button, html input[type="button"], /* 1 */ input[type="reset"], input[type="submit"] { -webkit-appearance: button; /* 2 */ cursor: pointer; /* 3 */ } /* * Re-set default cursor for disabled elements. */ button[disabled], input[disabled] { cursor: default; } /* * 1. Addresses box sizing set to `content-box` in IE 8/9. * 2. Removes excess padding in IE 8/9. */ input[type="checkbox"], input[type="radio"] { box-sizing: border-box; /* 1 */ padding: 0; /* 2 */ } /* * 1. Addresses `appearance` set to `searchfield` in Safari 5 and Chrome. * 2. Addresses `box-sizing` set to `border-box` in Safari 5 and Chrome * (include `-moz` to future-proof). */ input[type="search"] { -webkit-appearance: textfield; /* 1 */ -moz-box-sizing: content-box; -webkit-box-sizing: content-box; /* 2 */ box-sizing: content-box; } /* * Removes inner padding and search cancel button in Safari 5 and Chrome * on OS X. */ input[type="search"]::-webkit-search-cancel-button, input[type="search"]::-webkit-search-decoration { -webkit-appearance: none; } /* * Removes inner padding and border in Firefox 4+. */ button::-moz-focus-inner, input::-moz-focus-inner { border: 0; padding: 0; } /* * 1. Removes default vertical scrollbar in IE 8/9. * 2. Improves readability and alignment in all browsers. */ textarea { overflow: auto; /* 1 */ vertical-align: top; /* 2 */ } /* ========================================================================== Tables ========================================================================== */ /* * Remove most spacing between table cells. */ table { border-collapse: collapse; border-spacing: 0; } ================================================ FILE: docs/underscore-esm.html ================================================ underscore-esm.js
================================================ FILE: index.html ================================================ Underscore.js

Underscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects. It’s the answer to the question: “If I sit down in front of a blank HTML page, and want to start being productive immediately, what do I need?” … and the tie to go along with jQuery's tux and Backbone's suspenders.

Underscore provides over 100 functions that support both your favorite workaday functional helpers: map, filter, invoke — as well as more specialized goodies: function binding, javascript templating, creating quick indexes, deep equality testing, and so on.

A complete Test Suite is included for your perusal.

You may also read through the annotated source code. There is a modular version with clickable import references as well.

You may choose between monolithic and modular imports. There is a quick summary of the options below, as well as a more comprehensive discussion in the article.

Enjoying Underscore, and want to turn it up to 11? Try Underscore-contrib.

The project is hosted on GitHub. You can report bugs and discuss features on the issues page or chat in the Gitter channel.

You can support the project by donating on Patreon. Enterprise coverage is available as part of the Tidelift Subscription.

Underscore is an open-source component of DocumentCloud.

v1.13.8 Downloads (Right-click, and use "Save As")

65.9 KB, Uncompressed with Plentiful Comments  (Source Map)
8.59 KB, Minified and Gzipped  (Source Map)
68.4 KB, Uncompressed with Bountiful Comments  (Source Map)
7.48 KB, Minified and Gzipped  (Source Map)
Unreleased, current master, use by your own judgement and at your own risk
Unreleased, current master, use if you’re feeling lucky

v1.13.8 CDN URLs (Use with <script src="..."></script>)

In most cases, you can replace the version number above by latest so that your embed will automatically use the latest version, or stable if you want to delay updating until an update has proven to be free of accidental breaking changes. Example:
https://cdn.jsdelivr.net/npm/underscore@latest/underscore-umd-min.js

Package Installation

If you are hardcoding the path to the file within the package and you are unsure which build to use, it is very likely that you need underscore-umd.js or the minified variant underscore-umd-min.js.

Monolithic Import (recommended)

Modular Import

For functions with multiple aliases, the file name of the module is always the first name that appears in the documentation. For example, _.reduce/_.inject/_.foldl is exported from underscore/modules/reduce.js. Modular usage is mostly recommended for creating a customized build of Underscore.

Engine Compatibility

Underscore 1.x is backwards compatible with any engine that fully supports ES3, while also utilizing newer features when available, such as Object.keys, typed arrays and ES modules. We routinely run our unittests against the JavaScript engines listed below:

In addition:

Underscore 2.x will likely remove support for some outdated environments.

Collection Functions (Arrays or Objects)

each_.each(list, iteratee, [context]) Alias: forEach source
Iterates over a list of elements, yielding each in turn to an iteratee function. The iteratee is bound to the context object, if one is passed. Each invocation of iteratee is called with three arguments: (element, index, list). If list is a JavaScript object, iteratee's arguments will be (value, key, list). Returns the list for chaining.

_.each([1, 2, 3], alert);
=> alerts each number in turn...
_.each({one: 1, two: 2, three: 3}, alert);
=> alerts each number value in turn...

Note: Collection functions work on arrays, objects, and array-like objects such as arguments, NodeList and similar. But it works by duck-typing, so avoid passing objects with a numeric length property. It's also good to note that an each loop cannot be broken out of — to break, use _.find instead.

map_.map(list, iteratee, [context]) Alias: collect source
Produces a new array of values by mapping each value in list through a transformation function (iteratee). The iteratee is passed three arguments: the value, then the index (or key) of the iteration, and finally a reference to the entire list.

_.map([1, 2, 3], function(num){ return num * 3; });
=> [3, 6, 9]
_.map({one: 1, two: 2, three: 3}, function(num, key){ return num * 3; });
=> [3, 6, 9]
_.map([[1, 2], [3, 4]], _.first);
=> [1, 3]

reduce_.reduce(list, iteratee, [memo], [context]) Aliases: inject, foldl source
Also known as inject and foldl, reduce boils down a list of values into a single value. Memo is the initial state of the reduction, and each successive step of it should be returned by iteratee. The iteratee is passed four arguments: the memo, then the value and index (or key) of the iteration, and finally a reference to the entire list.

If no memo is passed to the initial invocation of reduce, the iteratee is not invoked on the first element of the list. The first element is instead passed as the memo in the invocation of the iteratee on the next element in the list.

var sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0);
=> 6

reduceRight_.reduceRight(list, iteratee, [memo], [context]) Alias: foldr source
The right-associative version of reduce. Foldr is not as useful in JavaScript as it would be in a language with lazy evaluation.

var list = [[0, 1], [2, 3], [4, 5]];
var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
=> [4, 5, 2, 3, 0, 1]

find_.find(list, predicate, [context]) Alias: detect source
Looks through each value in the list, returning the first one that passes a truth test (predicate), or undefined if no value passes the test. The function returns as soon as it finds an acceptable element, and doesn't traverse the entire list. predicate is transformed through iteratee to facilitate shorthand syntaxes.

var even = _.find([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> 2

filter_.filter(list, predicate, [context]) Alias: select source
Looks through each value in the list, returning an array of all the values that pass a truth test (predicate). predicate is transformed through iteratee to facilitate shorthand syntaxes.

var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> [2, 4, 6]

findWhere_.findWhere(list, properties) source
Looks through the list and returns the first value that matches all of the key-value pairs listed in properties.

If no match is found, or if list is empty, undefined will be returned.

_.findWhere(publicServicePulitzers, {newsroom: "The New York Times"});
=> {year: 1918, newsroom: "The New York Times",
  reason: "For its public service in publishing in full so many official reports,
  documents and speeches by European statesmen relating to the progress and
  conduct of the war."}

where_.where(list, properties) source
Looks through each value in the list, returning an array of all the values that matches the key-value pairs listed in properties.

_.where(listOfPlays, {author: "Shakespeare", year: 1611});
=> [{title: "Cymbeline", author: "Shakespeare", year: 1611},
    {title: "The Tempest", author: "Shakespeare", year: 1611}]

reject_.reject(list, predicate, [context]) source
Returns the values in list without the elements that the truth test (predicate) passes. The opposite of filter. predicate is transformed through iteratee to facilitate shorthand syntaxes.

var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> [1, 3, 5]

every_.every(list, [predicate], [context]) Alias: all source
Returns true if all of the values in the list pass the predicate truth test. Short-circuits and stops traversing the list if a false element is found. predicate is transformed through iteratee to facilitate shorthand syntaxes.

_.every([2, 4, 5], function(num) { return num % 2 == 0; });
=> false

some_.some(list, [predicate], [context]) Alias: any source
Returns true if any of the values in the list pass the predicate truth test. Short-circuits and stops traversing the list if a true element is found. predicate is transformed through iteratee to facilitate shorthand syntaxes.

_.some([null, 0, 'yes', false]);
=> true

contains_.contains(list, value, [fromIndex]) Aliases: include, includes source
Returns true if the value is present in the list. Uses indexOf internally, if list is an Array. Use fromIndex to start your search at a given index.

_.contains([1, 2, 3], 3);
=> true

invoke_.invoke(list, methodName, *arguments) source
Calls the method named by methodName on each value in the list. Any extra arguments passed to invoke will be forwarded on to the method invocation.

_.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
=> [[1, 5, 7], [1, 2, 3]]

pluck_.pluck(list, propertyName) source
A convenient version of what is perhaps the most common use-case for map: extracting a list of property values.

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.pluck(stooges, 'name');
=> ["moe", "larry", "curly"]

max_.max(list, [iteratee], [context]) source
Returns the maximum value in list. If an iteratee function is provided, it will be used on each value to generate the criterion by which the value is ranked. -Infinity is returned if list is empty, so an isEmpty guard may be required. This function can currently only compare numbers reliably. This function uses operator < (note).

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.max(stooges, function(stooge){ return stooge.age; });
=> {name: 'curly', age: 60};

min_.min(list, [iteratee], [context]) source
Returns the minimum value in list. If an iteratee function is provided, it will be used on each value to generate the criterion by which the value is ranked. Infinity is returned if list is empty, so an isEmpty guard may be required. This function can currently only compare numbers reliably. This function uses operator < (note).

var numbers = [10, 5, 100, 2, 1000];
_.min(numbers);
=> 2

sortBy_.sortBy(list, iteratee, [context]) source
Returns a (stably) sorted copy of list, ranked in ascending order by the results of running each value through iteratee. iteratee may also be the string name of the property to sort by (eg. length). This function uses operator < (note).

_.sortBy([1, 2, 3, 4, 5, 6], function(num){ return Math.sin(num); });
=> [5, 4, 6, 3, 1, 2]

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.sortBy(stooges, 'name');
=> [{name: 'curly', age: 60}, {name: 'larry', age: 50}, {name: 'moe', age: 40}];

groupBy_.groupBy(list, iteratee, [context]) source
Splits a collection into sets, grouped by the result of running each value through iteratee. If iteratee is a string instead of a function, groups by the property named by iteratee on each of the values.

_.groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); });
=> {1: [1.3], 2: [2.1, 2.4]}

_.groupBy(['one', 'two', 'three'], 'length');
=> {3: ["one", "two"], 5: ["three"]}

indexBy_.indexBy(list, iteratee, [context]) source
Given a list, and an iteratee function that returns a key for each element in the list (or a property name), returns an object with an index of each item. Just like groupBy, but for when you know your keys are unique.

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.indexBy(stooges, 'age');
=> {
  "40": {name: 'moe', age: 40},
  "50": {name: 'larry', age: 50},
  "60": {name: 'curly', age: 60}
}

countBy_.countBy(list, iteratee, [context]) source
Sorts a list into groups and returns a count for the number of objects in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.

_.countBy([1, 2, 3, 4, 5], function(num) {
  return num % 2 == 0 ? 'even': 'odd';
});
=> {odd: 3, even: 2}

shuffle_.shuffle(list) source
Returns a shuffled copy of the list, using a version of the Fisher-Yates shuffle.

_.shuffle([1, 2, 3, 4, 5, 6]);
=> [4, 1, 6, 3, 5, 2]

sample_.sample(list, [n]) source
Produce a random sample from the list. Pass a number to return n random elements from the list. Otherwise a single random item will be returned.

_.sample([1, 2, 3, 4, 5, 6]);
=> 4

_.sample([1, 2, 3, 4, 5, 6], 3);
=> [1, 6, 2]

toArray_.toArray(list) source
Creates a real Array from the list (anything that can be iterated over). Useful for transmuting the arguments object.

(function(){ return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
=> [2, 3, 4]

size_.size(list) source
Return the number of values in the list.

_.size([1, 2, 3, 4, 5]);
=> 5

_.size({one: 1, two: 2, three: 3});
=> 3

partition_.partition(list, predicate) source
Split list into two arrays: one whose elements all satisfy predicate and one whose elements all do not satisfy predicate. predicate is transformed through iteratee to facilitate shorthand syntaxes.

_.partition([0, 1, 2, 3, 4, 5], isOdd);
=> [[1, 3, 5], [0, 2, 4]]

compact_.compact(list) source
Returns a copy of the list with all falsy values removed. In JavaScript, false, null, 0, "", undefined and NaN are all falsy.

_.compact([0, 1, false, 2, '', 3]);
=> [1, 2, 3]

Array Functions

Note: All array functions will also work on the arguments object. However, Underscore functions are not designed to work on "sparse" arrays.

first_.first(array, [n]) Aliases: head, take source
Returns the first element of an array. Passing n will return the first n elements of the array.

_.first([5, 4, 3, 2, 1]);
=> 5

initial_.initial(array, [n]) source
Returns everything but the last entry of the array. Especially useful on the arguments object. Pass n to exclude the last n elements from the result.

_.initial([5, 4, 3, 2, 1]);
=> [5, 4, 3, 2]

last_.last(array, [n]) source
Returns the last element of an array. Passing n will return the last n elements of the array.

_.last([5, 4, 3, 2, 1]);
=> 1

rest_.rest(array, [index]) Aliases: tail, drop source
Returns the rest of the elements in an array. Pass an index to return the values of the array from that index onward.

_.rest([5, 4, 3, 2, 1]);
=> [4, 3, 2, 1]

flatten_.flatten(array, [depth]) source
Flattens a nested array. If you pass true or 1 as the depth, the array will only be flattened a single level. Passing a greater number will cause the flattening to descend deeper into the nesting hierarchy. Omitting the depth argument, or passing false or Infinity, flattens the array all the way to the deepest nesting level.

_.flatten([1, [2], [3, [[4]]]]);
=> [1, 2, 3, 4];

_.flatten([1, [2], [3, [[4]]]], true);
=> [1, 2, 3, [[4]]];

_.flatten([1, [2], [3, [[4]]]], 2);
=> [1, 2, 3, [4]];

without_.without(array, *values) source
Returns a copy of the array with all instances of the values removed.

_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
=> [2, 3, 4]

union_.union(*arrays) source
Computes the union of the passed-in arrays: the list of unique items, in order, that are present in one or more of the arrays.

_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2, 3, 101, 10]

intersection_.intersection(*arrays) source
Computes the list of values that are the intersection of all the arrays. Each value in the result is present in each of the arrays.

_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2]

difference_.difference(array, *others) source
Similar to without, but returns the values from array that are not present in the other arrays.

_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
=> [1, 3, 4]

uniq_.uniq(array, [isSorted], [iteratee]) Alias: unique source
Produces a duplicate-free version of the array, using === to test object equality. In particular only the first occurrence of each value is kept. If you know in advance that the array is sorted, passing true for isSorted will run a much faster algorithm. If you want to compute unique items based on a transformation, pass an iteratee function.

_.uniq([1, 2, 1, 4, 1, 3]);
=> [1, 2, 4, 3]

zip_.zip(*arrays) source
Merges together the values of each of the arrays with the values at the corresponding position. Useful when you have separate data sources that are coordinated through matching array indexes.

_.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);
=> [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]

unzip_.unzip(array) Alias: transpose source
The opposite of zip. Given an array of arrays, returns a series of new arrays, the first of which contains all of the first elements in the input arrays, the second of which contains all of the second elements, and so on. If you're working with a matrix of nested arrays, this can be used to transpose the matrix.

_.unzip([["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]);
=> [['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]]

object_.object(list, [values]) source
Converts arrays into objects. Pass either a single list of [key, value] pairs, or a list of keys, and a list of values. Passing by pairs is the reverse of pairs. If duplicate keys exist, the last value wins.

_.object(['moe', 'larry', 'curly'], [30, 40, 50]);
=> {moe: 30, larry: 40, curly: 50}

_.object([['moe', 30], ['larry', 40], ['curly', 50]]);
=> {moe: 30, larry: 40, curly: 50}

chunk_.chunk(array, length) source
Chunks an array into multiple arrays, each containing length or fewer items.

var partners = _.chunk(_.shuffle(kindergarten), 2);
=> [["Tyrone", "Elie"], ["Aidan", "Sam"], ["Katrina", "Billie"], ["Little Timmy"]]

indexOf_.indexOf(array, value, [isSorted]) source
Returns the index at which value can be found in the array, or -1 if value is not present in the array. If you're working with a large array, and you know that the array is already sorted, pass true for isSorted to use a faster binary search ... or, pass a number as the third argument in order to look for the first matching value in the array after the given index. If isSorted is true, this function uses operator < (note).

_.indexOf([1, 2, 3], 2);
=> 1

lastIndexOf_.lastIndexOf(array, value, [fromIndex]) source
Returns the index of the last occurrence of value in the array, or -1 if value is not present. Pass fromIndex to start your search at a given index.

_.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
=> 4

sortedIndex_.sortedIndex(array, value, [iteratee], [context]) source
Uses a binary search to determine the smallest index at which the value should be inserted into the array in order to maintain the array's sorted order. If an iteratee function is provided, it will be used to compute the sort ranking of each value, including the value you pass. The iteratee may also be the string name of the property to sort by (eg. length). This function uses operator < (note).

_.sortedIndex([10, 20, 30, 40, 50], 35);
=> 3

var stooges = [{name: 'moe', age: 40}, {name: 'curly', age: 60}];
_.sortedIndex(stooges, {name: 'larry', age: 50}, 'age');
=> 1

findIndex_.findIndex(array, predicate, [context]) source
Similar to _.indexOf, returns the first index where the predicate truth test passes; otherwise returns -1.

_.findIndex([4, 6, 8, 12], isPrime);
=> -1 // not found
_.findIndex([4, 6, 7, 12], isPrime);
=> 2

findLastIndex_.findLastIndex(array, predicate, [context]) source
Like _.findIndex but iterates the array in reverse, returning the index closest to the end where the predicate truth test passes.

var users = [{'id': 1, 'name': 'Bob', 'last': 'Brown'},
             {'id': 2, 'name': 'Ted', 'last': 'White'},
             {'id': 3, 'name': 'Frank', 'last': 'James'},
             {'id': 4, 'name': 'Ted', 'last': 'Jones'}];
_.findLastIndex(users, {
  name: 'Ted'
});
=> 3

range_.range([start], stop, [step]) source
A function to create flexibly-numbered lists of integers, handy for each and map loops. start, if omitted, defaults to 0; step defaults to 1 if start is before stop, otherwise -1. Returns a list of integers from start (inclusive) to stop (exclusive), incremented (or decremented) by step.

_.range(10);
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
_.range(1, 11);
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
_.range(0, 30, 5);
=> [0, 5, 10, 15, 20, 25]
_.range(0, -10, -1);
=> [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
_.range(0);
=> []

Function (uh, ahem) Functions

bind_.bind(function, object, *arguments) source
Bind a function to an object, meaning that whenever the function is called, the value of this will be the object. Optionally, pass arguments to the function to pre-fill them, also known as partial application. For partial application without context binding, use partial.

var func = function(greeting){ return greeting + ': ' + this.name };
func = _.bind(func, {name: 'moe'}, 'hi');
func();
=> 'hi: moe'

bindAll_.bindAll(object, *methodNames) source
Binds a number of methods on the object, specified by methodNames, to be run in the context of that object whenever they are invoked. Very handy for binding functions that are going to be used as event handlers, which would otherwise be invoked with a fairly useless this. methodNames are required.

var buttonView = {
  label  : 'underscore',
  onClick: function(){ alert('clicked: ' + this.label); },
  onHover: function(){ console.log('hovering: ' + this.label); }
};
_.bindAll(buttonView, 'onClick', 'onHover');
// When the button is clicked, this.label will have the correct value.
jQuery('#underscore_button').on('click', buttonView.onClick);

partial_.partial(function, *arguments) source
Partially apply a function by filling in any number of its arguments, without changing its dynamic this value. A close cousin of bind. You may pass _ in your list of arguments to specify an argument that should not be pre-filled, but left open to supply at call-time. Note: if you need _ placeholders and a this binding at the same time, use both _.partial and _.bind.

var subtract = function(a, b) { return b - a; };
sub5 = _.partial(subtract, 5);
sub5(20);
=> 15

// Using a placeholder
subFrom20 = _.partial(subtract, _, 20);
subFrom20(5);
=> 15

memoize_.memoize(function, [hashFunction]) source
Memoizes a given function by caching the computed result. Useful for speeding up slow-running computations. If passed an optional hashFunction, it will be used to compute the hash key for storing the result, based on the arguments to the original function. The default hashFunction just uses the first argument to the memoized function as the key. The cache of memoized values is available as the cache property on the returned function.

var fibonacci = _.memoize(function(n) {
  return n < 2 ? n: fibonacci(n - 1) + fibonacci(n - 2);
});

delay_.delay(function, wait, *arguments) source
Much like setTimeout, invokes function after wait milliseconds. If you pass the optional arguments, they will be forwarded on to the function when it is invoked.

var log = _.bind(console.log, console);
_.delay(log, 1000, 'logged later');
=> 'logged later' // Appears after one second.

defer_.defer(function, *arguments) source
Defers invoking the function until the current call stack has cleared, similar to using setTimeout with a delay of 0. Useful for performing expensive computations or HTML rendering in chunks without blocking the UI thread from updating. If you pass the optional arguments, they will be forwarded on to the function when it is invoked.

_.defer(function(){ alert('deferred'); });
// Returns from the function before the alert runs.

throttle_.throttle(function, wait, [options]) source
Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, will only actually call the original function at most once per every wait milliseconds. Useful for rate-limiting events that occur faster than you can keep up with.

By default, throttle will execute the function as soon as you call it for the first time, and, if you call it again any number of times during the wait period, as soon as that period is over. If you'd like to disable the leading-edge call, pass {leading: false}, and if you'd like to disable the execution on the trailing-edge, pass
{trailing: false}.

var throttled = _.throttle(updatePosition, 100);
$(window).scroll(throttled);

If you need to cancel a scheduled throttle, you can call .cancel() on the throttled function.

debounce_.debounce(function, wait, [immediate]) source
Creates and returns a new debounced version of the passed function which will postpone its execution until after wait milliseconds have elapsed since the last time it was invoked. Useful for implementing behavior that should only happen after the input has stopped arriving. For example: rendering a preview of a Markdown comment, recalculating a layout after the window has stopped being resized, and so on.

At the end of the wait interval, the function will be called with the arguments that were passed most recently to the debounced function.

Pass true for the immediate argument to cause debounce to trigger the function on the leading instead of the trailing edge of the wait interval. Useful in circumstances like preventing accidental double-clicks on a "submit" button from firing a second time.

var lazyLayout = _.debounce(calculateLayout, 300);
$(window).resize(lazyLayout);

If you need to cancel a scheduled debounce, you can call .cancel() on the debounced function.

once_.once(function) source
Creates a version of the function that can only be called one time. Repeated calls to the modified function will have no effect, returning the value from the original call. Useful for initialization functions, instead of having to set a boolean flag and then check it later.

var initialize = _.once(createApplication);
initialize();
initialize();
// Application is only created once.

after_.after(count, function) source
Creates a wrapper of function that does nothing at first. From the count-th call onwards, it starts actually calling function. Useful for grouping asynchronous responses, where you want to be sure that all the async calls have finished, before proceeding.

var renderNotes = _.after(notes.length, render);
_.each(notes, function(note) {
  note.asyncSave({success: renderNotes});
});
// renderNotes is run once, after all notes have saved.

before_.before(count, function) source
Creates a wrapper of function that memoizes its return value. From the count-th call onwards, the memoized result of the last invocation is returned immediately instead of invoking function again. So the wrapper will invoke function at most count - 1 times.

var monthlyMeeting = _.before(3, askForRaise);
monthlyMeeting();
monthlyMeeting();
monthlyMeeting();
// the result of any subsequent calls is the same as the second call

wrap_.wrap(function, wrapper) source
Wraps the first function inside of the wrapper function, passing it as the first argument. This allows the wrapper to execute code before and after the function runs, adjust the arguments, and execute it conditionally.

var hello = function(name) { return "hello: " + name; };
hello = _.wrap(hello, function(func) {
  return "before, " + func("moe") + ", after";
});
hello();
=> 'before, hello: moe, after'

negate_.negate(predicate) source
Returns a new negated version of the predicate function.

var isFalsy = _.negate(Boolean);
_.find([-2, -1, 0, 1, 2], isFalsy);
=> 0

compose_.compose(*functions) source
Returns the composition of a list of functions, where each function consumes the return value of the function that follows. In math terms, composing the functions f(), g(), and h() produces f(g(h())).

var greet    = function(name){ return "hi: " + name; };
var exclaim  = function(statement){ return statement.toUpperCase() + "!"; };
var welcome = _.compose(greet, exclaim);
welcome('moe');
=> 'hi: MOE!'

restArguments_.restArguments(function, [startIndex]) source
Returns a version of the function that, when called, receives all arguments from and beyond startIndex collected into a single array. If you don’t pass an explicit startIndex, it will be determined by looking at the number of arguments to the function itself. Similar to ES6’s rest parameters syntax.

var raceResults = _.restArguments(function(gold, silver, bronze, everyoneElse) {
  _.each(everyoneElse, sendConsolations);
});

raceResults("Dopey", "Grumpy", "Happy", "Sneezy", "Bashful", "Sleepy", "Doc");

Object Functions

keys_.keys(object) source
Retrieve all the names of the object's own enumerable properties.

_.keys({one: 1, two: 2, three: 3});
=> ["one", "two", "three"]

allKeys_.allKeys(object) source
Retrieve all the names of object's own and inherited properties.

function Stooge(name) {
  this.name = name;
}
Stooge.prototype.silly = true;
_.allKeys(new Stooge("Moe"));
=> ["name", "silly"]

values_.values(object) source
Return all of the values of the object's own properties.

_.values({one: 1, two: 2, three: 3});
=> [1, 2, 3]

mapObject_.mapObject(object, iteratee, [context]) source
Like map, but for objects. Transform the value of each property in turn.

_.mapObject({start: 5, end: 12}, function(val, key) {
  return val + 5;
});
=> {start: 10, end: 17}

pairs_.pairs(object) source
Convert an object into a list of [key, value] pairs. The opposite of object.

_.pairs({one: 1, two: 2, three: 3});
=> [["one", 1], ["two", 2], ["three", 3]]

invert_.invert(object) source
Returns a copy of the object where the keys have become the values and the values the keys. For this to work, all of your object's values should be unique and string serializable.

_.invert({Moe: "Moses", Larry: "Louis", Curly: "Jerome"});
=> {Moses: "Moe", Louis: "Larry", Jerome: "Curly"};

create_.create(prototype, props) source
Creates a new object with the given prototype, optionally attaching props as own properties. Basically, Object.create, but without all of the property descriptor jazz.

var moe = _.create(Stooge.prototype, {name: "Moe"});

functions_.functions(object) Alias: methods source
Returns a sorted list of the names of every method in an object — that is to say, the name of every function property of the object.

_.functions(_);
=> ["all", "any", "bind", "bindAll", "clone", "compact", "compose" ...

findKey_.findKey(object, predicate, [context]) source
Similar to _.findIndex but for keys in objects. Returns the key where the predicate truth test passes or undefined. predicate is transformed through iteratee to facilitate shorthand syntaxes.

extend_.extend(destination, *sources) source
Shallowly copy all of the properties in the source objects over to the destination object, and return the destination object. Any nested objects or arrays will be copied by reference, not duplicated. It's in-order, so the last source will override properties of the same name in previous arguments.

_.extend({name: 'moe'}, {age: 50});
=> {name: 'moe', age: 50}

extendOwn_.extendOwn(destination, *sources) Alias: assign source
Like extend, but only copies own properties over to the destination object.

pick_.pick(object, *keys) source
Return a copy of the object, filtered to only have values for the allowed keys (or array of valid keys). Alternatively accepts a predicate indicating which keys to pick.

_.pick({name: 'moe', age: 50, userid: 'moe1'}, 'name', 'age');
=> {name: 'moe', age: 50}
_.pick({name: 'moe', age: 50, userid: 'moe1'}, function(value, key, object) {
  return _.isNumber(value);
});
=> {age: 50}

omit_.omit(object, *keys) source
Return a copy of the object, filtered to omit the disallowed keys (or array of keys). Alternatively accepts a predicate indicating which keys to omit.

_.omit({name: 'moe', age: 50, userid: 'moe1'}, 'userid');
=> {name: 'moe', age: 50}
_.omit({name: 'moe', age: 50, userid: 'moe1'}, function(value, key, object) {
  return _.isNumber(value);
});
=> {name: 'moe', userid: 'moe1'}

defaults_.defaults(object, *defaults) source
Returns object after filling in its undefined properties with the first value present in the following list of defaults objects.

var iceCream = {flavor: "chocolate"};
_.defaults(iceCream, {flavor: "vanilla", sprinkles: "lots"});
=> {flavor: "chocolate", sprinkles: "lots"}

clone_.clone(object) source
Create a shallow-copied clone of the provided plain object. Any nested objects or arrays will be copied by reference, not duplicated.

_.clone({name: 'moe'});
=> {name: 'moe'};

tap_.tap(object, interceptor) source
Invokes interceptor with the object, and then returns object. The primary purpose of this method is to "tap into" a method chain, in order to perform operations on intermediate results within the chain.

_.chain([1,2,3,200])
  .filter(function(num) { return num % 2 == 0; })
  .tap(alert)
  .map(function(num) { return num * num })
  .value();
=> // [2, 200] (alerted)
=> [4, 40000]

toPath_.toPath(path) source
Ensures that path is an array. If path is a string, it is wrapped in a single-element array; if it is an array already, it is returned unmodified.

_.toPath('key');
=> ['key']
_.toPath(['a', 0, 'b']);
=> ['a', 0, 'b'] // (same array)

_.toPath is used internally in has, get, invoke, property, propertyOf and result, as well as in iteratee and all functions that depend on it, in order to normalize deep property paths. You can override _.toPath if you want to customize this behavior, for example to enable Lodash-like string path shorthands. Be advised that altering _.toPath will unavoidably cause some keys to become unreachable; override at your own risk.

// Support dotted path shorthands.
var originalToPath = _.toPath;
_.mixin({
  toPath: function(path) {
    return _.isString(path) ? path.split('.') : originalToPath(path);
  }
});
_.get({a: [{b: 5}]}, 'a.0.b');
=> 5

get_.get(object, path, [default]) source
Returns the specified property of object. path may be specified as a simple key, or as an array of object keys or array indexes, for deep property fetching. If the property does not exist or is undefined, the optional default is returned.

_.get({a: 10}, 'a');
=> 10
_.get({a: [{b: 2}]}, ['a', 0, 'b']);
=> 2
_.get({a: 10}, 'b', 100);
=> 100

has_.has(object, key) source
Does the object contain the given key? Identical to object.hasOwnProperty(key), but uses a safe reference to the hasOwnProperty function, in case it's been overridden accidentally.

_.has({a: 1, b: 2, c: 3}, "b");
=> true

property_.property(path) source
Returns a function that will return the specified property of any passed-in object. path may be specified as a simple key, or as an array of object keys or array indexes, for deep property fetching.

var stooge = {name: 'moe'};
'moe' === _.property('name')(stooge);
=> true

var stooges = {moe: {fears: {worst: 'Spiders'}}, curly: {fears: {worst: 'Moe'}}};
var curlysWorstFear = _.property(['curly', 'fears', 'worst']);
curlysWorstFear(stooges);
=> 'Moe'

propertyOf_.propertyOf(object) source
Inverse of _.property. Takes an object and returns a function which will return the value of a provided property.

var stooge = {name: 'moe'};
_.propertyOf(stooge)('name');
=> 'moe'

matcher_.matcher(attrs) Alias: matches source
Returns a predicate function that will tell you if a passed in object contains all of the key/value properties present in attrs.

var ready = _.matcher({selected: true, visible: true});
var readyToGoList = _.filter(list, ready);

isEqual_.isEqual(object, other) source
Performs an optimized deep comparison between the two objects, to determine if they should be considered equal.

var stooge = {name: 'moe', luckyNumbers: [13, 27, 34]};
var clone  = {name: 'moe', luckyNumbers: [13, 27, 34]};
stooge == clone;
=> false
_.isEqual(stooge, clone);
=> true

isMatch_.isMatch(object, properties) source
Tells you if the keys and values in properties are contained in object.

var stooge = {name: 'moe', age: 32};
_.isMatch(stooge, {age: 32});
=> true

isEmpty_.isEmpty(collection) source
Returns true if collection has no elements. For strings and array-like objects _.isEmpty checks if the length property is 0. For other objects, it returns true if the object has no enumerable own-properties. Note that primitive numbers, booleans and symbols are always empty by this definition.

_.isEmpty([1, 2, 3]);
=> false
_.isEmpty({});
=> true

isElement_.isElement(object) source
Returns true if object is a DOM element.

_.isElement(jQuery('body')[0]);
=> true

isArray_.isArray(object) source
Returns true if object is an Array.

(function(){ return _.isArray(arguments); })();
=> false
_.isArray([1,2,3]);
=> true

isObject_.isObject(value) source
Returns true if value is an Object. Note that JavaScript arrays and functions are objects, while (normal) strings and numbers are not.

_.isObject({});
=> true
_.isObject(1);
=> false

isArguments_.isArguments(object) source
Returns true if object is an Arguments object.

(function(){ return _.isArguments(arguments); })(1, 2, 3);
=> true
_.isArguments([1,2,3]);
=> false

isFunction_.isFunction(object) source
Returns true if object is a Function.

_.isFunction(alert);
=> true

isString_.isString(object) source
Returns true if object is a String.

_.isString("moe");
=> true

isNumber_.isNumber(object) source
Returns true if object is a Number (including NaN).

_.isNumber(8.4 * 5);
=> true

isFinite_.isFinite(object) source
Returns true if object is a finite Number.

_.isFinite(-101);
=> true

_.isFinite(-Infinity);
=> false

isBoolean_.isBoolean(object) source
Returns true if object is either true or false.

_.isBoolean(null);
=> false

isDate_.isDate(object) source
Returns true if object is a Date.

_.isDate(new Date());
=> true

isRegExp_.isRegExp(object) source
Returns true if object is a RegExp.

_.isRegExp(/moe/);
=> true

isError_.isError(object) source
Returns true if object inherits from an Error.

try {
  throw new TypeError("Example");
} catch (o_O) {
  _.isError(o_O);
}
=> true

isSymbol_.isSymbol(object) source
Returns true if object is a Symbol.

_.isSymbol(Symbol());
=> true

isMap_.isMap(object) source
Returns true if object is a Map.

_.isMap(new Map());
=> true

isWeakMap_.isWeakMap(object) source
Returns true if object is a WeakMap.

_.isWeakMap(new WeakMap());
=> true

isSet_.isSet(object) source
Returns true if object is a Set.

_.isSet(new Set());
=> true

isWeakSet_.isWeakSet(object) source
Returns true if object is a WeakSet.

_.isWeakSet(WeakSet());
=> true

isArrayBuffer_.isArrayBuffer(object) source
Returns true if object is an ArrayBuffer.

_.isArrayBuffer(new ArrayBuffer(8));
=> true

isDataView_.isDataView(object) source
Returns true if object is a DataView.

_.isDataView(new DataView(new ArrayBuffer(8)));
=> true

isTypedArray_.isTypedArray(object) source
Returns true if object is a TypedArray.

_.isTypedArray(new Int8Array(8));
=> true

isNaN_.isNaN(object) source
Returns true if object is NaN.
Note: this is not the same as the native isNaN function, which will also return true for many other not-number values, such as undefined.

_.isNaN(NaN);
=> true
isNaN(undefined);
=> true
_.isNaN(undefined);
=> false

isNull_.isNull(object) source
Returns true if the value of object is null.

_.isNull(null);
=> true
_.isNull(undefined);
=> false

isUndefined_.isUndefined(value) source
Returns true if value is undefined.

_.isUndefined(window.missingVariable);
=> true

Utility Functions

noConflict_.noConflict() source
Give control of the global _ variable back to its previous owner. Returns a reference to the Underscore object.

var underscore = _.noConflict();

The _.noConflict function is not present if you use the EcmaScript 6, AMD or CommonJS module system to import Underscore.

identity_.identity(value) source
Returns the same value that is used as the argument. In math: f(x) = x
This function looks useless, but is used throughout Underscore as a default iteratee.

var stooge = {name: 'moe'};
stooge === _.identity(stooge);
=> true

constant_.constant(value) source
Creates a function that returns the same value that is used as the argument of _.constant.

var stooge = {name: 'moe'};
stooge === _.constant(stooge)();
=> true

noop_.noop() source
Returns undefined irrespective of the arguments passed to it. Useful as the default for optional callback arguments.

obj.initialize = _.noop;

times_.times(n, iteratee, [context]) source
Invokes the given iteratee function n times. Each invocation of iteratee is called with an index argument. Produces an array of the returned values.

_.times(3, function(n){ genie.grantWishNumber(n); });

random_.random(min, max) source
Returns a random integer between min and max, inclusive. If you only pass one argument, it will return a number between 0 and that number.

_.random(0, 100);
=> 42

mixin_.mixin(object) source
Allows you to extend Underscore with your own utility functions. Pass a hash of {name: function} definitions to have your functions added to the Underscore object, as well as the OOP wrapper. Returns the Underscore object to facilitate chaining.

_.mixin({
  capitalize: function(string) {
    return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase();
  }
});
_("fabio").capitalize();
=> "Fabio"

iteratee_.iteratee(value, [context]) source
Generates a callback that can be applied to each element in a collection. _.iteratee supports a number of shorthand syntaxes for common callback use cases. Depending upon value's type, _.iteratee will return:

// No value
_.iteratee();
=> _.identity()

// Function
_.iteratee(function(n) { return n * 2; });
=> function(n) { return n * 2; }

// Object
_.iteratee({firstName: 'Chelsea'});
=> _.matcher({firstName: 'Chelsea'});

// Anything else
_.iteratee('firstName');
=> _.property('firstName');

The following Underscore methods transform their predicates through _.iteratee: countBy, every, filter, find, findIndex, findKey, findLastIndex, groupBy, indexBy, map, mapObject, max, min, partition, reject, some, sortBy, sortedIndex, and uniq

You may overwrite _.iteratee with your own custom function, if you want additional or different shorthand syntaxes:

// Support `RegExp` predicate shorthand.
var builtinIteratee = _.iteratee;
_.iteratee = function(value, context) {
  if (_.isRegExp(value)) return function(obj) { return value.test(obj) };
  return builtinIteratee(value, context);
};

uniqueId_.uniqueId([prefix]) source
Generate a globally-unique id for client-side models or DOM elements that need one. If prefix is passed, the id will be appended to it.

_.uniqueId('contact_');
=> 'contact_104'

escape_.escape(string) source
Escapes a string for insertion into HTML, replacing &, <, >, ", `, and ' characters.

_.escape('Curly, Larry & Moe');
=> "Curly, Larry &amp; Moe"

unescape_.unescape(string) source
The opposite of escape, replaces &amp;, &lt;, &gt;, &quot;, &#x60; and &#x27; with their unescaped counterparts.

_.unescape('Curly, Larry &amp; Moe');
=> "Curly, Larry & Moe"

result_.result(object, property, [defaultValue]) source
If the value of the named property is a function then invoke it with the object as context; otherwise, return it. If a default value is provided and the property doesn't exist or is undefined then the default will be returned. If defaultValue is a function its result will be returned.

var object = {cheese: 'crumpets', stuff: function(){ return 'nonsense'; }};
_.result(object, 'cheese');
=> "crumpets"
_.result(object, 'stuff');
=> "nonsense"
_.result(object, 'meat', 'ham');
=> "ham"

now_.now() source
Returns an integer timestamp for the current time, using the fastest method available in the runtime. Useful for implementing timing/animation functions.

_.now();
=> 1392066795351

template_.template(templateString, [settings]) source
Compiles JavaScript templates into functions that can be evaluated for rendering. Useful for rendering complicated bits of HTML from JSON data sources. Template functions can both interpolate values, using <%= … %>, as well as execute arbitrary JavaScript code, with <% … %>. If you wish to interpolate a value, and have it be HTML-escaped, use <%- … %>. When you evaluate a template function, pass in a data object that has properties corresponding to the template's free variables. The settings argument should be a hash containing any _.templateSettings that should be overridden.

var compiled = _.template("hello: <%= name %>");
compiled({name: 'moe'});
=> "hello: moe"

var template = _.template("<b><%- value %></b>");
template({value: '<script>'});
=> "<b>&lt;script&gt;</b>"

You can also use print from within JavaScript code. This is sometimes more convenient than using <%= ... %>.

var compiled = _.template("<% print('Hello ' + epithet); %>");
compiled({epithet: "stooge"});
=> "Hello stooge"

If ERB-style delimiters aren't your cup of tea, you can change Underscore's template settings to use different symbols to set off interpolated code. Define an interpolate regex to match expressions that should be interpolated verbatim, an escape regex to match expressions that should be inserted after being HTML-escaped, and an evaluate regex to match expressions that should be evaluated without insertion into the resulting string. Note that if part of your template matches more than one of these regexes, the first will be applied by the following order of priority: (1) escape, (2) interpolate, (3) evaluate. You may define or omit any combination of the three. For example, to perform Mustache.js-style templating:

_.templateSettings = {
  interpolate: /\{\{(.+?)\}\}/g
};

var template = _.template("Hello {{ name }}!");
template({name: "Mustache"});
=> "Hello Mustache!"

By default, template places the values from your data in the local scope via the with statement. However, you can specify a single variable name with the variable setting. This can significantly improve the speed at which a template is able to render.

_.template("Using 'with': <%= data.answer %>", {variable: 'data'})({answer: 'no'});
=> "Using 'with': no"

Precompiling your templates can be a big help when debugging errors you can't reproduce. This is because precompiled templates can provide line numbers and a stack trace, something that is not possible when compiling templates on the client. The source property is available on the compiled template function for easy precompilation.

<script>
  JST.project = <%= _.template(jstText).source %>;
</script>

VERSION
It is possible to get the current Underscore version via _.VERSION .

_.VERSION => 1.13.8

Object-Oriented Style

You can use Underscore in either an object-oriented or a functional style, depending on your preference. The following two lines of code are identical ways to double a list of numbers. source, source

_.map([1, 2, 3], function(n){ return n * 2; });
_([1, 2, 3]).map(function(n){ return n * 2; });

Chaining

Calling chain will cause all future method calls to return wrapped objects. When you've finished the computation, call value to retrieve the final value. Here's an example of chaining together a map/flatten/reduce, in order to get the word count of every word in a song.

var lyrics = [
  {line: 1, words: "I'm a lumberjack and I'm okay"},
  {line: 2, words: "I sleep all night and I work all day"},
  {line: 3, words: "He's a lumberjack and he's okay"},
  {line: 4, words: "He sleeps all night and he works all day"}
];

_.chain(lyrics)
  .map(function(line) { return line.words.split(' '); })
  .flatten()
  .reduce(function(counts, word) {
    counts[word] = (counts[word] || 0) + 1;
    return counts;
  }, {})
  .value();

=> {lumberjack: 2, all: 4, night: 2 ... }

In addition, the Array prototype's methods are proxied through the chained Underscore object, so you can slip a reverse or a push into your chain, and continue to modify the array.

chain_.chain(obj) source
Returns a wrapped object. Calling methods on this object will continue to return wrapped objects until value is called.

var stooges = [{name: 'curly', age: 25}, {name: 'moe', age: 21}, {name: 'larry', age: 23}];
var youngest = _.chain(stooges)
  .sortBy(function(stooge){ return stooge.age; })
  .map(function(stooge){ return stooge.name + ' is ' + stooge.age; })
  .first()
  .value();
=> "moe is 21"

value_.chain(obj).value() source
Extracts the value of a wrapped object.

_.chain([1, 2, 3]).reverse().value();
=> [3, 2, 1]

Underscore.lua, a Lua port of the functions that are applicable in both languages. Includes OOP-wrapping and chaining. (source)

Dollar.swift, a Swift port of many of the Underscore.js functions and more. (source)

Underscore.m, an Objective-C port of many of the Underscore.js functions, using a syntax that encourages chaining. (source)

_.m, an alternative Objective-C port that tries to stick a little closer to the original Underscore.js API. (source)

Underscore.php, a PHP port of the functions that are applicable in both languages. Tailored for PHP 5.4 and made with data-type tolerance in mind. (source)

Underscore-perl, a Perl port of many of the Underscore.js functions, aimed at on Perl hashes and arrays. (source)

Underscore.cfc, a Coldfusion port of many of the Underscore.js functions. (source)

Underscore.string, an Underscore extension that adds functions for string-manipulation: trim, startsWith, contains, capitalize, reverse, sprintf, and more.

Underscore-java, a java port of the functions that are applicable in both languages. Includes OOP-wrapping and chaining. (source)

Ruby's Enumerable module.

Prototype.js, which provides JavaScript with collection functions in the manner closest to Ruby's Enumerable.

Oliver Steele's Functional JavaScript, which includes comprehensive higher-order function support as well as string lambdas.

Michael Aufreiter's Data.js, a data manipulation + persistence library for JavaScript.

Python's itertools.

PyToolz, a Python port that extends itertools and functools to include much of the Underscore API.

Funcy, a practical collection of functional helpers for Python, partially inspired by Underscore.

Notes

On the use of < in Underscore
Underscore functions that depend on ordering, such as _.sortBy and _.sortedIndex, use JavaScript’s built-in relational operators, specifically the “less than” operator <. It is important to understand that these operators are only meaningful for numbers and strings. You can throw any value to them, but JavaScript will convert the operands to string or number first before performing the actual comparison. If you pass an operand that cannot be meaningfully converted to string or number, it ends up being NaN by default. This value is unsortable.

Ideally, the values that you are sorting should either be all (meaningfully convertible to) strings or all (meaningfully convertible to) numbers. If this is not the case, you have two options:

  • _.filter out all unsortable values first.
  • Pick a target type, i.e., either string or number, and pass an iteratee to your Underscore function that will convert its argument to a sensible instance of the target type. For example, if you have an array of numbers that you want to sort and that may occasionally contain null or undefined, you can control whether you want to sort these before or after all numbers by passing an iteratee to _.sortBy that returns -Infinity or +Infinity for such values, respectively. Or maybe you want to treat them as zeros; it is up to you. The same iteratee can also be passed to other Underscore functions to ensure that the behavior is consistent.

Change Log

1.13.8February 19, 2026DiffDocs

  • Fixes a security issue in _.flatten and _.isEqual that, under very specific circumstances, could allow for a Denial of Service (DoS) attack in server applications. This bug was present in all previous versions of Underscore. More details: CVE-2026-27601.
  • Adds documentation for _.VERSION.
  • Clarifies some terminology in the documentation for contributors.

1.13.7July 24, 2024DiffDocs

  • Fixes a bug where Underscore might throw an error on load if the executing environment overrides the native DataView.
  • Adds a direct link to the corresponding source code for each function in the documentation.
  • Clarifies the documentation for the step argument of the range function.
  • Adds dark mode support to the home page.
  • Other infrastructural improvements to funding, testing and building.

1.13.6September 24, 2022DiffDocs
Hotfix for version 1.13.5 to remove a postinstall script from the package.json, which unexpectedly broke many people's builds.

1.13.5September 23, 2022DiffDocs

  • Adds a module sub-entry to the package.json’s exports.require condition. When a bundling tool, such as Rollup with recent versions of @rollup/plugin-node-resolve, takes the exports map very literally, this should prevent situations in which the final bundle includes multiple copies of Underscore in different module formats.
  • Updates to the testing infrastructure and development dependencies.
  • No code changes.

1.13.4June 2, 2022DiffDocs

  • Fixes a compatibility issue with WebPack module federation.
  • Documentation improvements.

1.13.3April 23, 2022DiffDocs

  • Fixes a compatibility issue with ExtendScript.
  • Various improvements to testing and continuous integration, including the addition of security scanning and a reduced carbon footprint.

1.13.2December 16, 2021DiffDocs

  • Fixes a regression introduced in 1.9.0 that caused _.sample and _.shuffle to no longer work on strings.
  • Fixes an issue in IE8 compatibility code.
  • Makes the website mobile-friendly.
  • Various other minor documentation enhancements and a new test.

1.13.1April 15, 2021DiffDocs

  • Restores the underscore.js alias committed to the GitHub repository.
  • Adds some build clarifications to the documentation.
  • No code changes.

1.13.0April 9, 2021DiffDocs

  • Merges the changes from the 1.13.0-0 through 1.13.0-3 preview releases into the main release stream following version 1.12.1. As of this release, ESM support is 100%.
  • Adds a security policy to the documentation.
  • Adds funding information to the documentation.

1.13.0-3March 31, 2021DiffDocs

  • Adds a "module" exports condition to the package.json, which should theoretically help to avoid duplicate code bundling with exports-aware build tools.
  • Re-synchronizes some comments and documentation text with the 1.12.x branch.

1.13.0-2March 15, 2021DiffDocs

  • Fixes the same security issue in _.template as the parallel 1.12.1 release.

1.12.1March 15, 2021DiffDocs

  • Fixes a security issue in _.template that could enable a third party to inject code in compiled templates. This issue affects all versions of Underscore between 1.3.2 and 1.12.0, inclusive, as well as preview releases 1.13.0-0 and 1.13.0-1. The fix in this release is also included in the parallel preview release 1.13.0-2. CVE-2021-23358
  • Restores an optimization in _.debounce that was unintentionally lost in version 1.9.0 (same as in parallel preview release 1.13.0-0).
  • Various test and documentation enhancements (same as in parallel preview releases 1.13.0-0 and 1.13.0-1).

1.13.0-1March 11, 2021DiffDocs

  • Fixes an issue that caused aliases to be absent among the named exports in the new native ESM entry point for Node.js 12+.
  • More test and documentation fixes and enhancements.

1.13.0-0March 9, 2021DiffDocs

  • Adds experimental support for native ESM imports in Node.js. You can now also do named imports or even deep module imports directly from a Node.js process in Node.js version 12 and later. Monolithic imports are recommended for use in production. State (such as mixed-in functions) is shared between CommonJS and ESM consumers.
  • Renames the UMD bundle to underscore-umd.js for consistency with the other bundle names. An alias named underscore.js is retained for backwards compatibility.
  • Restores an optimization in _.debounce that was unintentionally lost in version 1.9.0.
  • Various test and documentation enhancements.

1.12.0November 24, 2020DiffDocs

  • Adds the _.get and _.toPath functions. The latter can be overridden in order to customize the interpretation of deep property paths throughout Underscore. A future version of Underscore-contrib will be providing a ready-made function for this purpose; users will be able to opt in to string-based path shorthands such as 'a.0.b' and 'a[0]["b"]' by using that function from Underscore-contrib to override _.toPath.
  • Fixes a bug in _.isEqual that caused typed arrays to compare equal when viewing different segments of the same underlying ArrayBuffer.
  • Improves the compatibility of _.isEqual, _.isDataView, _.isMap, _.isWeakMap and _.isSet with some older browsers, especially IE 11.
  • Significantly enhances the performance of _.isEmpty and several members of the isType family of functions.
  • Speeds up _.isEqual comparison of typed arrays and DataViews with idential buffer, byteOffset and byteLength.
  • Restores cross-browser testing during continuous integration to its former glory and adds documentation about engine compatibility.
  • Slims down the development dependencies for testing.

1.11.0August 28, 2020DiffDocsArticle

  • Puts the source of every function in a separate module, following up on the move to EcmaScript 6 export notation in version 1.10.0. AMD and CommonJS versions of the function modules are provided as well. This brings perfect treeshaking to all users and unlocks the possibility to create arbitrary custom Underscore builds without code size overhead. modules/index.js is still present and the UMD bundle is still recommended for most users.
    Since the modularization obfuscates the diff, piecewise diffs are provided below.
  • Adds a monolithic bundle in EcmaScript 6 module format, underscore-esm.js, as a modern alternative to the monolithic UMD bundle. Users who want to use ES module imports in the browser are advised to use this new bundle instead of modules/index.js, because underscore-esm.js provides the complete Underscore interface in a single download.
  • Adds a modular version of the annotated source, reflecting the full internal structure of the primary source code.
  • Adds _.isArrayBuffer, _.isDataView and _.isTypedArray functions, as well as support for the corresponding value types to _.isEqual.
  • Adds the option to flatten arrays to a specific depth: _.flatten(anArray, 3).
  • Adds _.transpose as an alias to _.unzip.
  • Fixes an inconsistency where Array.prototype methods on the Underscore wrapper would error when the wrapped value is null or undefined. These methods now perform a no-op on null values like the other Underscore functions.
  • Fixes a bug that caused _.first and _.last to return [] instead of undefined for empty arrays when used as an iteratee.
  • Fixes a regression introduced in version 1.9.0 that caused _.bindAll to return undefined instead of the bound object.
  • Restores continuous integration testing with Travis CI.
  • Replaces stigmatizing “whitelist”/“blacklist” terminology in comments and documentation by neutral “allowed”/“disallowed” terminology.
  • Various clarifications and minor enhancements and fixes to the documentation, source comments and a test.

1.10.2March 30, 2020DiffDocs

  • Fixes a bug introduced with 1.10.0, while using the legacy Node.js require API: var _ = require("underscore")._

1.10.1March 30, 2020DiffDocs

  • Fixed relative links among the ES Modules to include the file extension, for web browser support.

1.10.0March 30, 2020DiffDocs

  • Reformats the source code to use EcmaScript 6 export notation. The underscore.js UMD bundle is now compiled from underlying source modules instead of being the source. From now on, Rollup users have the option to import from the underlying source module in order to enable treeshaking.
  • Explicitly states in the documentation, and verifies in the unittests, that _.sortedIndex(array, value) always returns the lower bound, i.e., the smallest index, at which value may be inserted in array.
  • Makes the notation of the _.max unittest consistent with other unittests.
  • Fixes a bug that would cause infinite recursion if an overridden implementation of _.iteratee attempted to fall back to the original implementation.
  • Restores compatibility with EcmaScript 3 and ExtendScript.

1.9.2Jan 6, 2020DiffDocs

  • No code changes. Updated a test to help out CITGM.

1.9.1May 31, 2018DiffDocs

  • Fixes edge-case regressions from 1.9.0, including certain forms of calling _.first and _.last on an empty array, and passing arrays as keys to _.countBy and _.groupBy.

1.9.0April 18, 2018DiffDocs

  • Adds the _.restArguments function for variadic function handling.
  • Adds the _.chunk function for chunking up an array.
  • Adds a _.isSymbol, _.isMap, _.isWeakMap, _.isSet and _.isWeakSet functions.
  • _.throttle and _.debounce return functions that now have a .cancel() method, which can be used to cancel any scheduled calls.
  • _.property now accepts arrays of keys and indexes as path specifiers, for looking up a deep properties of a value.
  • _.range now accepts negative ranges to generate descending arrays.
  • Adds support for several environments including: WebWorkers, browserify and ES6 imports.
  • Removes the component.json as the Component package management system is discontinued.
  • The placeholder used for partial is now configurable by setting _.partial.placeholder.
  • _.bindAll now accepts arrays or arguments for keys.
  • Three years of performance improvements.

1.8.3April 2, 2015DiffDocs

  • Adds an _.create method, as a slimmed down version of Object.create.
  • Works around an iOS bug that can improperly cause isArrayLike to be JIT-ed. Also fixes a bug when passing 0 to isArrayLike.

1.8.2Feb. 22, 2015DiffDocs

  • Restores the previous old-Internet-Explorer edge cases changed in 1.8.1.
  • Adds a fromIndex argument to _.contains.

1.8.1Feb. 19, 2015DiffDocs

  • Fixes/changes some old-Internet Explorer and related edge case behavior. Test your app with Underscore 1.8.1 in an old IE and let us know how it's doing...

1.8.0Feb. 19, 2015DiffDocs

  • Added _.mapObject, which is similar to _.map, but just for the values in your object. (A real crowd pleaser.)
  • Added _.allKeys which returns all the enumerable property names on an object.
  • Reverted a 1.7.0 change where _.extend only copied "own" properties. Hopefully this will un-break you — if it breaks you again, I apologize.
  • Added _.extendOwn — a less-useful form of _.extend that only copies over "own" properties.
  • Added _.findIndex and _.findLastIndex functions, which nicely complement their twin-twins _.indexOf and _.lastIndexOf.
  • Added an _.isMatch predicate function that tells you if an object matches key-value properties. A kissing cousin of _.isEqual and _.matcher.
  • Added an _.isError function.
  • Restored the _.unzip function as the inverse of zip. Flip-flopping. I know.
  • _.result now takes an optional fallback value (or function that provides the fallback value).
  • Added the _.propertyOf function generator as a mirror-world version of _.property.
  • Deprecated _.matches. It's now known by a more harmonious name — _.matcher.
  • Various and diverse code simplifications, changes for improved cross-platform compatibility, and edge case bug fixes.

1.7.0August 26, 2014DiffDocs

  • For consistency and speed across browsers, Underscore now ignores native array methods for forEach, map, reduce, reduceRight, filter, every, some, indexOf, and lastIndexOf. "Sparse" arrays are officially dead in Underscore.
  • Added _.iteratee to customize the iterators used by collection functions. Many Underscore methods will take a string argument for easier _.property-style lookups, an object for _.where-style filtering, or a function as a custom callback.
  • Added _.before as a counterpart to _.after.
  • Added _.negate to invert the truth value of a passed-in predicate.
  • Added _.noop as a handy empty placeholder function.
  • _.isEmpty now works with arguments objects.
  • _.has now guards against nullish objects.
  • _.omit can now take an iteratee function.
  • _.partition is now called with index and object.
  • _.matches creates a shallow clone of your object and only iterates over own properties.
  • Aligning better with the forthcoming ECMA6 Object.assign, _.extend only iterates over the object's own properties.
  • Falsy guards are no longer needed in _.extend and _.defaults—if the passed in argument isn't a JavaScript object it's just returned.
  • Fixed a few edge cases in _.max and _.min to handle arrays containing NaN (like strings or other objects) and Infinity and -Infinity.
  • Override base methods like each and some and they'll be used internally by other Underscore functions too.
  • The escape functions handle backticks (`), to deal with an IE ≤ 8 bug.
  • For consistency, _.union and _.difference now only work with arrays and not variadic args.
  • _.memoize exposes the cache of memoized values as a property on the returned function.
  • _.pick accepts iteratee and context arguments for a more advanced callback.
  • Underscore templates no longer accept an initial data object. _.template always returns a function now.
  • Optimizations and code cleanup aplenty.

1.6.0February 10, 2014DiffDocs

  • Underscore now registers itself for AMD (Require.js), Bower and Component, as well as being a CommonJS module and a regular (Java)Script. An ugliness, but perhaps a necessary one.
  • Added _.partition, a way to split a collection into two lists of results — those that pass and those that fail a particular predicate.
  • Added _.property, for easy creation of iterators that pull specific properties from objects. Useful in conjunction with other Underscore collection functions.
  • Added _.matches, a function that will give you a predicate that can be used to tell if a given object matches a list of specified key/value properties.
  • Added _.constant, as a higher-order _.identity.
  • Added _.now, an optimized way to get a timestamp — used internally to speed up debounce and throttle.
  • The _.partial function may now be used to partially apply any of its arguments, by passing _ wherever you'd like a placeholder variable, to be filled-in later.
  • The _.each function now returns a reference to the list for chaining.
  • The _.keys function now returns an empty array for non-objects instead of throwing.
  • … and more miscellaneous refactoring.

1.5.2September 7, 2013DiffDocs

  • Added an indexBy function, which fits in alongside its cousins, countBy and groupBy.
  • Added a sample function, for sampling random elements from arrays.
  • Some optimizations relating to functions that can be implemented in terms of _.keys (which includes, significantly, each on objects). Also for debounce in a tight loop.
  • The _.escape function no longer escapes '/'.

1.5.1July 8, 2013DiffDocs

  • Removed unzip, as it's simply the application of zip to an array of arguments. Use _.zip.apply(_, list) to transpose instead.

1.5.0July 6, 2013DiffDocs

  • Added a new unzip function, as the inverse of _.zip.
  • The throttle function now takes an options argument, allowing you to disable execution of the throttled function on either the leading or trailing edge.
  • A source map is now supplied for easier debugging of the minified production build of Underscore.
  • The defaults function now only overrides undefined values, not null ones.
  • Removed the ability to call _.bindAll with no method name arguments. It's pretty much always wiser to allow the names of the methods you'd like to bind.
  • Removed the ability to call _.after with an invocation count of zero. The minimum number of calls is (naturally) now 1.

1.4.4January 30, 2013DiffDocs

  • Added _.findWhere, for finding the first element in a list that matches a particular set of keys and values.
  • Added _.partial, for partially applying a function without changing its dynamic reference to this.
  • Simplified bind by removing some edge cases involving constructor functions. In short: don't _.bind your constructors.
  • A minor optimization to invoke.
  • Fix bug in the minified version due to the minifier incorrectly optimizing-away isFunction.

1.4.3December 4, 2012DiffDocs

  • Improved Underscore compatibility with Adobe's JS engine that can be used to script Illustrator, Photoshop, and friends.
  • Added a default _.identity iterator to countBy and groupBy.
  • The uniq function can now take array, iterator, context as the argument list.
  • The times function now returns the mapped array of iterator results.
  • Simplified and fixed bugs in throttle.

1.4.2October 6, 2012DiffDocs

  • For backwards compatibility, returned to pre-1.4.0 behavior when passing null to iteration functions. They now become no-ops again.

1.4.1October 1, 2012DiffDocs

  • Fixed a 1.4.0 regression in the lastIndexOf function.

1.4.0September 27, 2012DiffDocs

  • Added a pairs function, for turning a JavaScript object into [key, value] pairs ... as well as an object function, for converting an array of [key, value] pairs into an object.
  • Added a countBy function, for counting the number of objects in a list that match a certain criteria.
  • Added an invert function, for performing a simple inversion of the keys and values in an object.
  • Added a where function, for easy cases of filtering a list for objects with specific values.
  • Added an omit function, for filtering an object to remove certain keys.
  • Added a random function, to return a random number in a given range.
  • _.debounce'd functions now return their last updated value, just like _.throttle'd functions do.
  • The sortBy function now runs a stable sort algorithm.
  • Added the optional fromIndex option to indexOf and lastIndexOf.
  • "Sparse" arrays are no longer supported in Underscore iteration functions. Use a for loop instead (or better yet, an object).
  • The min and max functions may now be called on very large arrays.
  • Interpolation in templates now represents null and undefined as the empty string.
  • Underscore iteration functions no longer accept null values as a no-op argument. You'll get an early error instead.
  • A number of edge-cases fixes and tweaks, which you can spot in the diff. Depending on how you're using Underscore, 1.4.0 may be more backwards-incompatible than usual — please test when you upgrade.

1.3.3April 10, 2012DiffDocs

  • Many improvements to _.template, which now provides the source of the template function as a property, for potentially even more efficient pre-compilation on the server-side. You may now also set the variable option when creating a template, which will cause your passed-in data to be made available under the variable you named, instead of using a with statement — significantly improving the speed of rendering the template.
  • Added the pick function, which allows you to filter an object literal with a list of allowed property names.
  • Added the result function, for convenience when working with APIs that allow either functions or raw properties.
  • Added the isFinite function, because sometimes knowing that a value is a number just ain't quite enough.
  • The sortBy function may now also be passed the string name of a property to use as the sort order on each object.
  • Fixed uniq to work with sparse arrays.
  • The difference function now performs a shallow flatten instead of a deep one when computing array differences.
  • The debounce function now takes an immediate parameter, which will cause the callback to fire on the leading instead of the trailing edge.

1.3.1January 23, 2012DiffDocs

  • Added an _.has function, as a safer way to use hasOwnProperty.
  • Added _.collect as an alias for _.map. Smalltalkers, rejoice.
  • Reverted an old change so that _.extend will correctly copy over keys with undefined values again.
  • Bugfix to stop escaping slashes within interpolations in _.template.

1.3.0January 11, 2012DiffDocs

  • Removed AMD (RequireJS) support from Underscore. If you'd like to use Underscore with RequireJS, you can load it as a normal script, wrap or patch your copy, or download a forked version.

1.2.4January 4, 2012DiffDocs

  • You now can (and probably should, as it's simpler) write _.chain(list) instead of _(list).chain().
  • Fix for escaped characters in Underscore templates, and for supporting customizations of _.templateSettings that only define one or two of the required regexes.
  • Fix for passing an array as the first argument to an _.wrap'd function.
  • Improved compatibility with ClojureScript, which adds a call function to String.prototype.

1.2.3December 7, 2011DiffDocs

  • Dynamic scope is now preserved for compiled _.template functions, so you can use the value of this if you like.
  • Sparse array support of _.indexOf, _.lastIndexOf.
  • Both _.reduce and _.reduceRight can now be passed an explicitly undefined value. (There's no reason why you'd want to do this.)

1.2.2November 14, 2011DiffDocs

  • Continued tweaks to _.isEqual semantics. Now JS primitives are considered equivalent to their wrapped versions, and arrays are compared by their numeric properties only (#351).
  • _.escape no longer tries to be smart about not double-escaping already-escaped HTML entities. Now it just escapes regardless (#350).
  • In _.template, you may now leave semicolons out of evaluated statements if you wish: <% }) %> (#369).
  • _.after(callback, 0) will now trigger the callback immediately, making "after" easier to use with asynchronous APIs (#366).

1.2.1October 24, 2011DiffDocs

  • Several important bug fixes for _.isEqual, which should now do better on mutated Arrays, and on non-Array objects with length properties. (#329)
  • James Burke contributed Underscore exporting for AMD module loaders, and Tony Lukasavage for Appcelerator Titanium. (#335, #338)
  • You can now _.groupBy(list, 'property') as a shortcut for grouping values by a particular common property.
  • _.throttle'd functions now fire immediately upon invocation, and are rate-limited thereafter (#170, #266).
  • Most of the _.is[Type] checks no longer ducktype.
  • The _.bind function now also works on constructors, a-la ES5 ... but you would never want to use _.bind on a constructor function.
  • _.clone no longer wraps non-object types in Objects.
  • _.find and _.filter are now the preferred names for _.detect and _.select.

1.2.0October 5, 2011DiffDocs

  • The _.isEqual function now supports true deep equality comparisons, with checks for cyclic structures, thanks to Kit Cambridge.
  • Underscore templates now support HTML escaping interpolations, using <%- ... %> syntax.
  • Ryan Tenney contributed _.shuffle, which uses a modified Fisher-Yates to give you a shuffled copy of an array.
  • _.uniq can now be passed an optional iterator, to determine by what criteria an object should be considered unique.
  • _.last now takes an optional argument which will return the last N elements of the list.
  • A new _.initial function was added, as a mirror of _.rest, which returns all the initial values of a list (except the last N).

1.1.7July 13, 2011DiffDocs
Added _.groupBy, which aggregates a collection into groups of like items. Added _.union and _.difference, to complement the (re-named) _.intersection. Various improvements for support of sparse arrays. _.toArray now returns a clone, if directly passed an array. _.functions now also returns the names of functions that are present in the prototype chain.

1.1.6April 18, 2011DiffDocs
Added _.after, which will return a function that only runs after first being called a specified number of times. _.invoke can now take a direct function reference. _.every now requires an iterator function to be passed, which mirrors the ES5 API. _.extend no longer copies keys when the value is undefined. _.bind now errors when trying to bind an undefined value.

1.1.5March 20, 2011DiffDocs
Added an _.defaults function, for use merging together JS objects representing default options. Added an _.once function, for manufacturing functions that should only ever execute a single time. _.bind now delegates to the native ES5 version, where available. _.keys now throws an error when used on non-Object values, as in ES5. Fixed a bug with _.keys when used over sparse arrays.

1.1.4January 9, 2011DiffDocs
Improved compliance with ES5's Array methods when passing null as a value. _.wrap now correctly sets this for the wrapped function. _.indexOf now takes an optional flag for finding the insertion index in an array that is guaranteed to already be sorted. Avoiding the use of .callee, to allow _.isArray to work properly in ES5's strict mode.

1.1.3December 1, 2010DiffDocs
In CommonJS, Underscore may now be required with just:
var _ = require("underscore"). Added _.throttle and _.debounce functions. Removed _.breakLoop, in favor of an ES5-style un-break-able each implementation — this removes the try/catch, and you'll now have better stack traces for exceptions that are thrown within an Underscore iterator. Improved the isType family of functions for better interoperability with Internet Explorer host objects. _.template now correctly escapes backslashes in templates. Improved _.reduce compatibility with the ES5 version: if you don't pass an initial value, the first item in the collection is used. _.each no longer returns the iterated collection, for improved consistency with ES5's forEach.

1.1.2October 15, 2010DiffDocs
Fixed _.contains, which was mistakenly pointing at _.intersect instead of _.include, like it should have been. Added _.unique as an alias for _.uniq.

1.1.1October 5, 2010DiffDocs
Improved the speed of _.template, and its handling of multiline interpolations. Ryan Tenney contributed optimizations to many Underscore functions. An annotated version of the source code is now available.

1.1.0August 18, 2010DiffDocs
The method signature of _.reduce has been changed to match the ES5 signature, instead of the Ruby/Prototype.js version. This is a backwards-incompatible change. _.template may now be called with no arguments, and preserves whitespace. _.contains is a new alias for _.include.

1.0.4June 22, 2010DiffDocs
Andri Möll contributed the _.memoize function, which can be used to speed up expensive repeated computations by caching the results.

1.0.3June 14, 2010DiffDocs
Patch that makes _.isEqual return false if any property of the compared object has a NaN value. Technically the correct thing to do, but of questionable semantics. Watch out for NaN comparisons.

1.0.2March 23, 2010DiffDocs
Fixes _.isArguments in recent versions of Opera, which have arguments objects as real Arrays.

1.0.1March 19, 2010DiffDocs
Bugfix for _.isEqual, when comparing two objects with the same number of undefined keys, but with different names.

1.0.0March 18, 2010DiffDocs
Things have been stable for many months now, so Underscore is now considered to be out of beta, at 1.0. Improvements since 0.6 include _.isBoolean, and the ability to have _.extend take multiple source objects.

0.6.0February 24, 2010DiffDocs
Major release. Incorporates a number of Mile Frawley's refactors for safer duck-typing on collection functions, and cleaner internals. A new _.mixin method that allows you to extend Underscore with utility functions of your own. Added _.times, which works the same as in Ruby or Prototype.js. Native support for ES5's Array.isArray, and Object.keys.

0.5.8January 28, 2010DiffDocs
Fixed Underscore's collection functions to work on NodeLists and HTMLCollections once more, thanks to Justin Tulloss.

0.5.7January 20, 2010DiffDocs
A safer implementation of _.isArguments, and a faster _.isNumber,
thanks to Jed Schmidt.

0.5.6January 18, 2010DiffDocs
Customizable delimiters for _.template, contributed by Noah Sloan.

0.5.5January 9, 2010DiffDocs
Fix for a bug in MobileSafari's OOP-wrapper, with the arguments object.

0.5.4January 5, 2010DiffDocs
Fix for multiple single quotes within a template string for _.template. See: Rick Strahl's blog post.

0.5.2January 1, 2010DiffDocs
New implementations of isArray, isDate, isFunction, isNumber, isRegExp, and isString, thanks to a suggestion from Robert Kieffer. Instead of doing Object#toString comparisons, they now check for expected properties, which is less safe, but more than an order of magnitude faster. Most other Underscore functions saw minor speed improvements as a result. Evgeniy Dolzhenko contributed _.tap, similar to Ruby 1.9's, which is handy for injecting side effects (like logging) into chained calls.

0.5.1December 9, 2009DiffDocs
Added an _.isArguments function. Lots of little safety checks and optimizations contributed by Noah Sloan and Andri Möll.

0.5.0December 7, 2009DiffDocs
[API Changes] _.bindAll now takes the context object as its first parameter. If no method names are passed, all of the context object's methods are bound to it, enabling chaining and easier binding. _.functions now takes a single argument and returns the names of its Function properties. Calling _.functions(_) will get you the previous behavior. Added _.isRegExp so that isEqual can now test for RegExp equality. All of the "is" functions have been shrunk down into a single definition. Karl Guertin contributed patches.

0.4.7December 6, 2009DiffDocs
Added isDate, isNaN, and isNull, for completeness. Optimizations for isEqual when checking equality between Arrays or Dates. _.keys is now 25%–2X faster (depending on your browser) which speeds up the functions that rely on it, such as _.each.

0.4.6November 30, 2009DiffDocs
Added the range function, a port of the Python function of the same name, for generating flexibly-numbered lists of integers. Original patch contributed by Kirill Ishanov.

0.4.5November 19, 2009DiffDocs
Added rest for Arrays and arguments objects, and aliased first as head, and rest as tail, thanks to Luke Sutton's patches. Added tests ensuring that all Underscore Array functions also work on arguments objects.

0.4.4November 18, 2009DiffDocs
Added isString, and isNumber, for consistency. Fixed _.isEqual(NaN, NaN) to return true (which is debatable).

0.4.3November 9, 2009DiffDocs
Started using the native StopIteration object in browsers that support it. Fixed Underscore setup for CommonJS environments.

0.4.2November 9, 2009DiffDocs
Renamed the unwrapping function to value, for clarity.

0.4.1November 8, 2009DiffDocs
Chained Underscore objects now support the Array prototype methods, so that you can perform the full range of operations on a wrapped array without having to break your chain. Added a breakLoop method to break in the middle of any Underscore iteration. Added an isEmpty function that works on arrays and objects.

0.4.0November 7, 2009DiffDocs
All Underscore functions can now be called in an object-oriented style, like so: _([1, 2, 3]).map(...);. Original patch provided by Marc-André Cournoyer. Wrapped objects can be chained through multiple method invocations. A functions method was added, providing a sorted list of all the functions in Underscore.

0.3.3October 31, 2009DiffDocs
Added the JavaScript 1.8 function reduceRight. Aliased it as foldr, and aliased reduce as foldl.

0.3.2October 29, 2009DiffDocs
Now runs on stock Rhino interpreters with: load("underscore.js"). Added identity as a utility function.

0.3.1October 29, 2009DiffDocs
All iterators are now passed in the original collection as their third argument, the same as JavaScript 1.6's forEach. Iterating over objects is now called with (value, key, collection), for details see _.each.

0.3.0October 29, 2009DiffDocs
Added Dmitry Baranovskiy's comprehensive optimizations, merged in Kris Kowal's patches to make Underscore CommonJS and Narwhal compliant.

0.2.0October 28, 2009DiffDocs
Added compose and lastIndexOf, renamed inject to reduce, added aliases for inject, filter, every, some, and forEach.

0.1.1October 28, 2009DiffDocs
Added noConflict, so that the "Underscore" object can be assigned to other variables.

0.1.0October 28, 2009Docs
Initial release of Underscore.js.

A DocumentCloud Project

================================================ FILE: karma.conf-sauce.js ================================================ var _ = require('./'); // Browsers to run on Sauce Labs platforms // (See https://saucelabs.com/platform/supported-browsers-devices for an // up-to-date overview of supported versions of browsers and platforms.) var sauceBrowsers = _.reduce([ ['firefox', 'latest'], ['firefox', '60'], ['firefox', '40'], ['firefox', '11'], // ['firefox', '4'], // failing due to "not enough arguments" ['chrome', 'latest'], ['chrome', '60'], ['chrome', '40'], ['chrome', '26'], // latest Edge as well as pre-Blink versions ['microsoftedge', 'latest', 'Windows 10'], ['microsoftedge', '18', 'Windows 10'], ['microsoftedge', '13', 'Windows 10'], ['internet explorer', 'latest', 'Windows 10'], ['internet explorer', '10', 'Windows 8'], ['internet explorer', '9', 'Windows 7'], // Older versions of IE no longer supported by Sauce Labs ['safari', 'latest', 'macOS 10.15'], ['safari', '12', 'macOS 10.14'], ['safari', '11', 'macOS 10.13'], ['safari', '8', 'OS X 10.10'], ], function(memo, platform) { // internet explorer -> ie var label = platform[0].split(' '); if (label.length > 1) { label = _.invoke(label, 'charAt', 0) } label = (label.join("") + '_v' + platform[1]).replace(' ', '_').toUpperCase(); memo[label] = _.pick({ 'base': 'SauceLabs', 'browserName': platform[0], 'version': platform[1], 'platform': platform[2] }, Boolean); return memo; }, {}); module.exports = function(config) { if ( !process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY ) { console.log('Sauce environments not set --- Skipping'); return process.exit(0); } config.set({ basePath: '', frameworks: ['qunit'], singleRun: true, browserDisconnectTolerance: 5, browserNoActivityTimeout: 240000, // list of files / patterns to load in the browser files: [ 'test/vendor/qunit-extras.js', 'test/qunit-setup.js', 'test/overrides.js', 'underscore-umd.js', 'test/*.js' ], // Number of sauce tests to start in parallel concurrency: 9, // test results reporter to use reporters: ['dots', 'saucelabs'], port: 9876, colors: true, logLevel: config.LOG_INFO, sauceLabs: { build: 'TRAVIS #' + process.env.TRAVIS_BUILD_NUMBER + ' (' + process.env.TRAVIS_BUILD_ID + ')', startConnect: true, tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER }, captureTimeout: 120000, customLaunchers: sauceBrowsers, // Browsers to launch, commented out to prevent karma from starting // too many concurrent browsers and timing sauce out. browsers: _.keys(sauceBrowsers) }); }; ================================================ FILE: karma.conf.js ================================================ // Note some browser launchers should be installed before using karma start. // For example: // $ npm install karma-firefox-launcher // $ karma start --browser=Firefox // See https://karma-runner.github.io/0.8/config/configuration-file.html module.exports = function(config) { config.set({ basePath: '', frameworks: ['qunit'], logLevel: config.LOG_INFO, port: 9876, // list of files / patterns to load in the browser files: [ 'test/qunit-setup.js', 'test/overrides.js', 'underscore-umd.js', 'test/*.js' ], // Test results reporter to use // https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['PhantomJS'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: true }); }; ================================================ FILE: modules/.eslintrc ================================================ { "parserOptions": { "ecmaVersion": 6, "sourceType": "module", }, "plugins": [ "import" ], "extends": [ "plugin:import/errors" ], "rules": { // ExtendScript wrongly gives equal precedence to && and ||. #2949 "no-mixed-operators": [ "error", { "groups": [["&&", "||"]] } ] } } ================================================ FILE: modules/_baseCreate.js ================================================ import isObject from './isObject.js'; import { nativeCreate } from './_setup.js'; // Create a naked function reference for surrogate-prototype-swapping. function ctor() { return function(){}; } // An internal function for creating a new object that inherits from another. export default function baseCreate(prototype) { if (!isObject(prototype)) return {}; if (nativeCreate) return nativeCreate(prototype); var Ctor = ctor(); Ctor.prototype = prototype; var result = new Ctor; Ctor.prototype = null; return result; } ================================================ FILE: modules/_baseIteratee.js ================================================ import identity from './identity.js'; import isFunction from './isFunction.js'; import isObject from './isObject.js'; import isArray from './isArray.js'; import matcher from './matcher.js'; import property from './property.js'; import optimizeCb from './_optimizeCb.js'; // An internal function to generate callbacks that can be applied to each // element in a collection, returning the desired result — either `_.identity`, // an arbitrary callback, a property matcher, or a property accessor. export default function baseIteratee(value, context, argCount) { if (value == null) return identity; if (isFunction(value)) return optimizeCb(value, context, argCount); if (isObject(value) && !isArray(value)) return matcher(value); return property(value); } ================================================ FILE: modules/_cb.js ================================================ import _ from './underscore.js'; import baseIteratee from './_baseIteratee.js'; import iteratee from './iteratee.js'; // The function we call internally to generate a callback. It invokes // `_.iteratee` if overridden, otherwise `baseIteratee`. export default function cb(value, context, argCount) { if (_.iteratee !== iteratee) return _.iteratee(value, context); return baseIteratee(value, context, argCount); } ================================================ FILE: modules/_chainResult.js ================================================ import _ from './underscore.js'; // Helper function to continue chaining intermediate results. export default function chainResult(instance, obj) { return instance._chain ? _(obj).chain() : obj; } ================================================ FILE: modules/_collectNonEnumProps.js ================================================ import { nonEnumerableProps, ObjProto } from './_setup.js'; import isFunction from './isFunction.js'; import has from './_has.js'; // Internal helper to create a simple lookup structure. // `collectNonEnumProps` used to depend on `_.contains`, but this led to // circular imports. `emulatedSet` is a one-off solution that only works for // arrays of strings. function emulatedSet(keys) { var hash = {}; for (var l = keys.length, i = 0; i < l; ++i) hash[keys[i]] = true; return { contains: function(key) { return hash[key] === true; }, push: function(key) { hash[key] = true; return keys.push(key); } }; } // Internal helper. Checks `keys` for the presence of keys in IE < 9 that won't // be iterated by `for key in ...` and thus missed. Extends `keys` in place if // needed. export default function collectNonEnumProps(obj, keys) { keys = emulatedSet(keys); var nonEnumIdx = nonEnumerableProps.length; var constructor = obj.constructor; var proto = (isFunction(constructor) && constructor.prototype) || ObjProto; // Constructor is a special case. var prop = 'constructor'; if (has(obj, prop) && !keys.contains(prop)) keys.push(prop); while (nonEnumIdx--) { prop = nonEnumerableProps[nonEnumIdx]; if (prop in obj && obj[prop] !== proto[prop] && !keys.contains(prop)) { keys.push(prop); } } } ================================================ FILE: modules/_createAssigner.js ================================================ // An internal function for creating assigner functions. export default function createAssigner(keysFunc, defaults) { return function(obj) { var length = arguments.length; if (defaults) obj = Object(obj); if (length < 2 || obj == null) return obj; for (var index = 1; index < length; index++) { var source = arguments[index], keys = keysFunc(source), l = keys.length; for (var i = 0; i < l; i++) { var key = keys[i]; if (!defaults || obj[key] === void 0) obj[key] = source[key]; } } return obj; }; } ================================================ FILE: modules/_createEscaper.js ================================================ import keys from './keys.js'; // Internal helper to generate functions for escaping and unescaping strings // to/from HTML interpolation. export default function createEscaper(map) { var escaper = function(match) { return map[match]; }; // Regexes for identifying a key that needs to be escaped. var source = '(?:' + keys(map).join('|') + ')'; var testRegexp = RegExp(source); var replaceRegexp = RegExp(source, 'g'); return function(string) { string = string == null ? '' : '' + string; return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; }; } ================================================ FILE: modules/_createIndexFinder.js ================================================ import getLength from './_getLength.js'; import { slice } from './_setup.js'; import isNaN from './isNaN.js'; // Internal function to generate the `_.indexOf` and `_.lastIndexOf` functions. export default function createIndexFinder(dir, predicateFind, sortedIndex) { return function(array, item, idx) { var i = 0, length = getLength(array); if (typeof idx == 'number') { if (dir > 0) { i = idx >= 0 ? idx : Math.max(idx + length, i); } else { length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1; } } else if (sortedIndex && idx && length) { idx = sortedIndex(array, item); return array[idx] === item ? idx : -1; } if (item !== item) { idx = predicateFind(slice.call(array, i, length), isNaN); return idx >= 0 ? idx + i : -1; } for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) { if (array[idx] === item) return idx; } return -1; }; } ================================================ FILE: modules/_createPredicateIndexFinder.js ================================================ import cb from './_cb.js'; import getLength from './_getLength.js'; // Internal function to generate `_.findIndex` and `_.findLastIndex`. export default function createPredicateIndexFinder(dir) { return function(array, predicate, context) { predicate = cb(predicate, context); var length = getLength(array); var index = dir > 0 ? 0 : length - 1; for (; index >= 0 && index < length; index += dir) { if (predicate(array[index], index, array)) return index; } return -1; }; } ================================================ FILE: modules/_createReduce.js ================================================ import isArrayLike from './_isArrayLike.js'; import keys from './keys.js'; import optimizeCb from './_optimizeCb.js'; // Internal helper to create a reducing function, iterating left or right. export default function createReduce(dir) { // Wrap code that reassigns argument variables in a separate function than // the one that accesses `arguments.length` to avoid a perf hit. (#1991) var reducer = function(obj, iteratee, memo, initial) { var _keys = !isArrayLike(obj) && keys(obj), length = (_keys || obj).length, index = dir > 0 ? 0 : length - 1; if (!initial) { memo = obj[_keys ? _keys[index] : index]; index += dir; } for (; index >= 0 && index < length; index += dir) { var currentKey = _keys ? _keys[index] : index; memo = iteratee(memo, obj[currentKey], currentKey, obj); } return memo; }; return function(obj, iteratee, memo, context) { var initial = arguments.length >= 3; return reducer(obj, optimizeCb(iteratee, context, 4), memo, initial); }; } ================================================ FILE: modules/_createSizePropertyCheck.js ================================================ import { MAX_ARRAY_INDEX } from './_setup.js'; // Common internal logic for `isArrayLike` and `isBufferLike`. export default function createSizePropertyCheck(getSizeProperty) { return function(collection) { var sizeProperty = getSizeProperty(collection); return typeof sizeProperty == 'number' && sizeProperty >= 0 && sizeProperty <= MAX_ARRAY_INDEX; } } ================================================ FILE: modules/_deepGet.js ================================================ // Internal function to obtain a nested property in `obj` along `path`. export default function deepGet(obj, path) { var length = path.length; for (var i = 0; i < length; i++) { if (obj == null) return void 0; obj = obj[path[i]]; } return length ? obj : void 0; } ================================================ FILE: modules/_escapeMap.js ================================================ // Internal list of HTML entities for escaping. export default { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', '`': '`' }; ================================================ FILE: modules/_executeBound.js ================================================ import baseCreate from './_baseCreate.js'; import isObject from './isObject.js'; // Internal function to execute `sourceFunc` bound to `context` with optional // `args`. Determines whether to execute a function as a constructor or as a // normal function. export default function executeBound(sourceFunc, boundFunc, context, callingContext, args) { if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args); var self = baseCreate(sourceFunc.prototype); var result = sourceFunc.apply(self, args); if (isObject(result)) return result; return self; } ================================================ FILE: modules/_flatten.js ================================================ import getLength from './_getLength.js'; import isArrayLike from './_isArrayLike.js'; import isArray from './isArray.js'; import isArguments from './isArguments.js'; // Internal implementation of a `flatten` function. export default function flatten(input, depth, strict) { if (!depth && depth !== 0) depth = Infinity; // We will be avoiding recursive calls because this could be exploited to // cause a stack overflow (CVE-2026-27601). Instead, we "trampoline" on an // explicit stack. var output = [], idx = 0, i = 0, length = getLength(input) || 0, stack = []; while (true) { if (i >= length) { if (!stack.length) break; var frame = stack.pop(); i = frame.i; input = frame.v; length = getLength(input); continue; } var value = input[i++]; if (stack.length >= depth) { output[idx++] = value; } else if (isArrayLike(value) && (isArray(value) || isArguments(value))) { // Flatten current level of array or arguments object. stack.push({i: i, v: input}); i = 0; input = value; length = getLength(input); } else if (!strict) { output[idx++] = value; } } return output; } ================================================ FILE: modules/_getByteLength.js ================================================ import shallowProperty from './_shallowProperty.js'; // Internal helper to obtain the `byteLength` property of an object. export default shallowProperty('byteLength'); ================================================ FILE: modules/_getLength.js ================================================ import shallowProperty from './_shallowProperty.js'; // Internal helper to obtain the `length` property of an object. export default shallowProperty('length'); ================================================ FILE: modules/_group.js ================================================ import cb from './_cb.js'; import each from './each.js'; // An internal function used for aggregate "group by" operations. export default function group(behavior, partition) { return function(obj, iteratee, context) { var result = partition ? [[], []] : {}; iteratee = cb(iteratee, context); each(obj, function(value, index) { var key = iteratee(value, index, obj); behavior(result, value, key); }); return result; }; } ================================================ FILE: modules/_has.js ================================================ import { hasOwnProperty } from './_setup.js'; // Internal function to check whether `key` is an own property name of `obj`. export default function has(obj, key) { return obj != null && hasOwnProperty.call(obj, key); } ================================================ FILE: modules/_hasObjectTag.js ================================================ import tagTester from './_tagTester.js'; export default tagTester('Object'); ================================================ FILE: modules/_isArrayLike.js ================================================ import createSizePropertyCheck from './_createSizePropertyCheck.js'; import getLength from './_getLength.js'; // Internal helper for collection methods to determine whether a collection // should be iterated as an array or as an object. // Related: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094 export default createSizePropertyCheck(getLength); ================================================ FILE: modules/_isBufferLike.js ================================================ import createSizePropertyCheck from './_createSizePropertyCheck.js'; import getByteLength from './_getByteLength.js'; // Internal helper to determine whether we should spend extensive checks against // `ArrayBuffer` et al. export default createSizePropertyCheck(getByteLength); ================================================ FILE: modules/_keyInObj.js ================================================ // Internal `_.pick` helper function to determine whether `key` is an enumerable // property name of `obj`. export default function keyInObj(value, key, obj) { return key in obj; } ================================================ FILE: modules/_methodFingerprint.js ================================================ import getLength from './_getLength.js'; import isFunction from './isFunction.js'; import allKeys from './allKeys.js'; // Since the regular `Object.prototype.toString` type tests don't work for // some types in IE 11, we use a fingerprinting heuristic instead, based // on the methods. It's not great, but it's the best we got. // The fingerprint method lists are defined below. export function ie11fingerprint(methods) { var length = getLength(methods); return function(obj) { if (obj == null) return false; // `Map`, `WeakMap` and `Set` have no enumerable keys. var keys = allKeys(obj); if (getLength(keys)) return false; for (var i = 0; i < length; i++) { if (!isFunction(obj[methods[i]])) return false; } // If we are testing against `WeakMap`, we need to ensure that // `obj` doesn't have a `forEach` method in order to distinguish // it from a regular `Map`. return methods !== weakMapMethods || !isFunction(obj[forEachName]); }; } // In the interest of compact minification, we write // each string in the fingerprints only once. var forEachName = 'forEach', hasName = 'has', commonInit = ['clear', 'delete'], mapTail = ['get', hasName, 'set']; // `Map`, `WeakMap` and `Set` each have slightly different // combinations of the above sublists. export var mapMethods = commonInit.concat(forEachName, mapTail), weakMapMethods = commonInit.concat(mapTail), setMethods = ['add'].concat(commonInit, forEachName, hasName); ================================================ FILE: modules/_optimizeCb.js ================================================ // Internal function that returns an efficient (for current engines) version // of the passed-in callback, to be repeatedly applied in other Underscore // functions. export default function optimizeCb(func, context, argCount) { if (context === void 0) return func; switch (argCount == null ? 3 : argCount) { case 1: return function(value) { return func.call(context, value); }; // The 2-argument case is omitted because we’re not using it. case 3: return function(value, index, collection) { return func.call(context, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(context, accumulator, value, index, collection); }; } return function() { return func.apply(context, arguments); }; } ================================================ FILE: modules/_setup.js ================================================ // Current version. export var VERSION = '1.13.8'; // Establish the root object, `window` (`self`) in the browser, `global` // on the server, or `this` in some virtual machines. We use `self` // instead of `window` for `WebWorker` support. export var root = (typeof self == 'object' && self.self === self && self) || (typeof global == 'object' && global.global === global && global) || Function('return this')() || {}; // Save bytes in the minified (but not gzipped) version: export var ArrayProto = Array.prototype, ObjProto = Object.prototype; export var SymbolProto = typeof Symbol !== 'undefined' ? Symbol.prototype : null; // Create quick reference variables for speed access to core prototypes. export var push = ArrayProto.push, slice = ArrayProto.slice, toString = ObjProto.toString, hasOwnProperty = ObjProto.hasOwnProperty; // Modern feature detection. export var supportsArrayBuffer = typeof ArrayBuffer !== 'undefined', supportsDataView = typeof DataView !== 'undefined'; // All **ECMAScript 5+** native function implementations that we hope to use // are declared here. export var nativeIsArray = Array.isArray, nativeKeys = Object.keys, nativeCreate = Object.create, nativeIsView = supportsArrayBuffer && ArrayBuffer.isView; // Create references to these builtin functions because we override them. export var _isNaN = isNaN, _isFinite = isFinite; // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed. export var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString'); export var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString', 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString']; // The largest integer that can be represented exactly. export var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1; ================================================ FILE: modules/_shallowProperty.js ================================================ // Internal helper to generate a function to obtain property `key` from `obj`. export default function shallowProperty(key) { return function(obj) { return obj == null ? void 0 : obj[key]; }; } ================================================ FILE: modules/_stringTagBug.js ================================================ import { supportsDataView } from './_setup.js'; import hasObjectTag from './_hasObjectTag.js'; // In IE 10 - Edge 13, `DataView` has string tag `'[object Object]'`. // In IE 11, the most common among them, this problem also applies to // `Map`, `WeakMap` and `Set`. // Also, there are cases where an application can override the native // `DataView` object, in cases like that we can't use the constructor // safely and should just rely on alternate `DataView` checks export var hasDataViewBug = ( supportsDataView && (!/\[native code\]/.test(String(DataView)) || hasObjectTag(new DataView(new ArrayBuffer(8)))) ), isIE11 = (typeof Map !== 'undefined' && hasObjectTag(new Map)); ================================================ FILE: modules/_tagTester.js ================================================ import { toString } from './_setup.js'; // Internal function for creating a `toString`-based type tester. export default function tagTester(name) { var tag = '[object ' + name + ']'; return function(obj) { return toString.call(obj) === tag; }; } ================================================ FILE: modules/_toBufferView.js ================================================ import getByteLength from './_getByteLength.js'; // Internal function to wrap or shallow-copy an ArrayBuffer, // typed array or DataView to a new view, reusing the buffer. export default function toBufferView(bufferSource) { return new Uint8Array( bufferSource.buffer || bufferSource, bufferSource.byteOffset || 0, getByteLength(bufferSource) ); } ================================================ FILE: modules/_toPath.js ================================================ import _ from './underscore.js'; import './toPath.js'; // Internal wrapper for `_.toPath` to enable minification. // Similar to `cb` for `_.iteratee`. export default function toPath(path) { return _.toPath(path); } ================================================ FILE: modules/_unescapeMap.js ================================================ import invert from './invert.js'; import escapeMap from './_escapeMap.js'; // Internal list of HTML entities for unescaping. export default invert(escapeMap); ================================================ FILE: modules/after.js ================================================ // Returns a function that will only be executed on and after the Nth call. export default function after(times, func) { return function() { if (--times < 1) { return func.apply(this, arguments); } }; } ================================================ FILE: modules/allKeys.js ================================================ import isObject from './isObject.js'; import { hasEnumBug } from './_setup.js'; import collectNonEnumProps from './_collectNonEnumProps.js'; // Retrieve all the enumerable property names of an object. export default function allKeys(obj) { if (!isObject(obj)) return []; var keys = []; for (var key in obj) keys.push(key); // Ahem, IE < 9. if (hasEnumBug) collectNonEnumProps(obj, keys); return keys; } ================================================ FILE: modules/before.js ================================================ // Returns a function that will only be executed up to (but not including) the // Nth call. export default function before(times, func) { var memo; return function() { if (--times > 0) { memo = func.apply(this, arguments); } if (times <= 1) func = null; return memo; }; } ================================================ FILE: modules/bind.js ================================================ import restArguments from './restArguments.js'; import isFunction from './isFunction.js'; import executeBound from './_executeBound.js'; // Create a function bound to a given object (assigning `this`, and arguments, // optionally). export default restArguments(function(func, context, args) { if (!isFunction(func)) throw new TypeError('Bind must be called on a function'); var bound = restArguments(function(callArgs) { return executeBound(func, bound, context, this, args.concat(callArgs)); }); return bound; }); ================================================ FILE: modules/bindAll.js ================================================ import restArguments from './restArguments.js'; import flatten from './_flatten.js'; import bind from './bind.js'; // Bind a number of an object's methods to that object. Remaining arguments // are the method names to be bound. Useful for ensuring that all callbacks // defined on an object belong to it. export default restArguments(function(obj, keys) { keys = flatten(keys, false, false); var index = keys.length; if (index < 1) throw new Error('bindAll must be passed function names'); while (index--) { var key = keys[index]; obj[key] = bind(obj[key], obj); } return obj; }); ================================================ FILE: modules/chain.js ================================================ import _ from './underscore.js'; // Start chaining a wrapped Underscore object. export default function chain(obj) { var instance = _(obj); instance._chain = true; return instance; } ================================================ FILE: modules/chunk.js ================================================ import { slice } from './_setup.js'; // Chunk a single array into multiple arrays, each containing `count` or fewer // items. export default function chunk(array, count) { if (count == null || count < 1) return []; var result = []; var i = 0, length = array.length; while (i < length) { result.push(slice.call(array, i, i += count)); } return result; } ================================================ FILE: modules/clone.js ================================================ import isObject from './isObject.js'; import isArray from './isArray.js'; import extend from './extend.js'; // Create a (shallow-cloned) duplicate of an object. export default function clone(obj) { if (!isObject(obj)) return obj; return isArray(obj) ? obj.slice() : extend({}, obj); } ================================================ FILE: modules/compact.js ================================================ import filter from './filter.js'; // Trim out all falsy values from an array. export default function compact(array) { return filter(array, Boolean); } ================================================ FILE: modules/compose.js ================================================ // Returns a function that is the composition of a list of functions, each // consuming the return value of the function that follows. export default function compose() { var args = arguments; var start = args.length - 1; return function() { var i = start; var result = args[start].apply(this, arguments); while (i--) result = args[i].call(this, result); return result; }; } ================================================ FILE: modules/constant.js ================================================ // Predicate-generating function. Often useful outside of Underscore. export default function constant(value) { return function() { return value; }; } ================================================ FILE: modules/contains.js ================================================ import isArrayLike from './_isArrayLike.js'; import values from './values.js'; import indexOf from './indexOf.js'; // Determine if the array or object contains a given item (using `===`). export default function contains(obj, item, fromIndex, guard) { if (!isArrayLike(obj)) obj = values(obj); if (typeof fromIndex != 'number' || guard) fromIndex = 0; return indexOf(obj, item, fromIndex) >= 0; } ================================================ FILE: modules/countBy.js ================================================ import group from './_group.js'; import has from './_has.js'; // Counts instances of an object that group by a certain criterion. Pass // either a string attribute to count by, or a function that returns the // criterion. export default group(function(result, value, key) { if (has(result, key)) result[key]++; else result[key] = 1; }); ================================================ FILE: modules/create.js ================================================ import baseCreate from './_baseCreate.js'; import extendOwn from './extendOwn.js'; // Creates an object that inherits from the given prototype object. // If additional properties are provided then they will be added to the // created object. export default function create(prototype, props) { var result = baseCreate(prototype); if (props) extendOwn(result, props); return result; } ================================================ FILE: modules/debounce.js ================================================ import restArguments from './restArguments.js'; import now from './now.js'; // When a sequence of calls of the returned function ends, the argument // function is triggered. The end of a sequence is defined by the `wait` // parameter. If `immediate` is passed, the argument function will be // triggered at the beginning of the sequence instead of at the end. export default function debounce(func, wait, immediate) { var timeout, previous, args, result, context; var later = function() { var passed = now() - previous; if (wait > passed) { timeout = setTimeout(later, wait - passed); } else { timeout = null; if (!immediate) result = func.apply(context, args); // This check is needed because `func` can recursively invoke `debounced`. if (!timeout) args = context = null; } }; var debounced = restArguments(function(_args) { context = this; args = _args; previous = now(); if (!timeout) { timeout = setTimeout(later, wait); if (immediate) result = func.apply(context, args); } return result; }); debounced.cancel = function() { clearTimeout(timeout); timeout = args = context = null; }; return debounced; } ================================================ FILE: modules/defaults.js ================================================ import createAssigner from './_createAssigner.js'; import allKeys from './allKeys.js'; // Fill in a given object with default properties. export default createAssigner(allKeys, true); ================================================ FILE: modules/defer.js ================================================ import partial from './partial.js'; import delay from './delay.js'; import _ from './underscore.js'; // Defers a function, scheduling it to run after the current call stack has // cleared. export default partial(delay, _, 1); ================================================ FILE: modules/delay.js ================================================ import restArguments from './restArguments.js'; // Delays a function for the given number of milliseconds, and then calls // it with the arguments supplied. export default restArguments(function(func, wait, args) { return setTimeout(function() { return func.apply(null, args); }, wait); }); ================================================ FILE: modules/difference.js ================================================ import restArguments from './restArguments.js'; import flatten from './_flatten.js'; import filter from './filter.js'; import contains from './contains.js'; // Take the difference between one array and a number of other arrays. // Only the elements present in just the first array will remain. export default restArguments(function(array, rest) { rest = flatten(rest, true, true); return filter(array, function(value){ return !contains(rest, value); }); }); ================================================ FILE: modules/each.js ================================================ import optimizeCb from './_optimizeCb.js'; import isArrayLike from './_isArrayLike.js'; import keys from './keys.js'; // The cornerstone for collection functions, an `each` // implementation, aka `forEach`. // Handles raw objects in addition to array-likes. Treats all // sparse array-likes as if they were dense. export default function each(obj, iteratee, context) { iteratee = optimizeCb(iteratee, context); var i, length; if (isArrayLike(obj)) { for (i = 0, length = obj.length; i < length; i++) { iteratee(obj[i], i, obj); } } else { var _keys = keys(obj); for (i = 0, length = _keys.length; i < length; i++) { iteratee(obj[_keys[i]], _keys[i], obj); } } return obj; } ================================================ FILE: modules/escape.js ================================================ import createEscaper from './_createEscaper.js'; import escapeMap from './_escapeMap.js'; // Function for escaping strings to HTML interpolation. export default createEscaper(escapeMap); ================================================ FILE: modules/every.js ================================================ import cb from './_cb.js'; import isArrayLike from './_isArrayLike.js'; import keys from './keys.js'; // Determine whether all of the elements pass a truth test. export default function every(obj, predicate, context) { predicate = cb(predicate, context); var _keys = !isArrayLike(obj) && keys(obj), length = (_keys || obj).length; for (var index = 0; index < length; index++) { var currentKey = _keys ? _keys[index] : index; if (!predicate(obj[currentKey], currentKey, obj)) return false; } return true; } ================================================ FILE: modules/extend.js ================================================ import createAssigner from './_createAssigner.js'; import allKeys from './allKeys.js'; // Extend a given object with all the properties in passed-in object(s). export default createAssigner(allKeys); ================================================ FILE: modules/extendOwn.js ================================================ import createAssigner from './_createAssigner.js'; import keys from './keys.js'; // Assigns a given object with all the own properties in the passed-in // object(s). // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) export default createAssigner(keys); ================================================ FILE: modules/filter.js ================================================ import cb from './_cb.js'; import each from './each.js'; // Return all the elements that pass a truth test. export default function filter(obj, predicate, context) { var results = []; predicate = cb(predicate, context); each(obj, function(value, index, list) { if (predicate(value, index, list)) results.push(value); }); return results; } ================================================ FILE: modules/find.js ================================================ import isArrayLike from './_isArrayLike.js'; import findIndex from './findIndex.js'; import findKey from './findKey.js'; // Return the first value which passes a truth test. export default function find(obj, predicate, context) { var keyFinder = isArrayLike(obj) ? findIndex : findKey; var key = keyFinder(obj, predicate, context); if (key !== void 0 && key !== -1) return obj[key]; } ================================================ FILE: modules/findIndex.js ================================================ import createPredicateIndexFinder from './_createPredicateIndexFinder.js'; // Returns the first index on an array-like that passes a truth test. export default createPredicateIndexFinder(1); ================================================ FILE: modules/findKey.js ================================================ import cb from './_cb.js'; import keys from './keys.js'; // Returns the first key on an object that passes a truth test. export default function findKey(obj, predicate, context) { predicate = cb(predicate, context); var _keys = keys(obj), key; for (var i = 0, length = _keys.length; i < length; i++) { key = _keys[i]; if (predicate(obj[key], key, obj)) return key; } } ================================================ FILE: modules/findLastIndex.js ================================================ import createPredicateIndexFinder from './_createPredicateIndexFinder.js'; // Returns the last index on an array-like that passes a truth test. export default createPredicateIndexFinder(-1); ================================================ FILE: modules/findWhere.js ================================================ import find from './find.js'; import matcher from './matcher.js'; // Convenience version of a common use case of `_.find`: getting the first // object containing specific `key:value` pairs. export default function findWhere(obj, attrs) { return find(obj, matcher(attrs)); } ================================================ FILE: modules/first.js ================================================ import initial from './initial.js'; // Get the first element of an array. Passing **n** will return the first N // values in the array. The **guard** check allows it to work with `_.map`. export default function first(array, n, guard) { if (array == null || array.length < 1) return n == null || guard ? void 0 : []; if (n == null || guard) return array[0]; return initial(array, array.length - n); } ================================================ FILE: modules/flatten.js ================================================ import _flatten from './_flatten.js'; // Flatten out an array, either recursively (by default), or up to `depth`. // Passing `true` or `false` as `depth` means `1` or `Infinity`, respectively. export default function flatten(array, depth) { return _flatten(array, depth, false); } ================================================ FILE: modules/functions.js ================================================ import isFunction from './isFunction.js'; // Return a sorted list of the function names available on the object. export default function functions(obj) { var names = []; for (var key in obj) { if (isFunction(obj[key])) names.push(key); } return names.sort(); } ================================================ FILE: modules/get.js ================================================ import toPath from './_toPath.js'; import deepGet from './_deepGet.js'; import isUndefined from './isUndefined.js'; // Get the value of the (deep) property on `path` from `object`. // If any property in `path` does not exist or if the value is // `undefined`, return `defaultValue` instead. // The `path` is normalized through `_.toPath`. export default function get(object, path, defaultValue) { var value = deepGet(object, toPath(path)); return isUndefined(value) ? defaultValue : value; } ================================================ FILE: modules/groupBy.js ================================================ import group from './_group.js'; import has from './_has.js'; // Groups the object's values by a criterion. Pass either a string attribute // to group by, or a function that returns the criterion. export default group(function(result, value, key) { if (has(result, key)) result[key].push(value); else result[key] = [value]; }); ================================================ FILE: modules/has.js ================================================ import _has from './_has.js'; import toPath from './_toPath.js'; // Shortcut function for checking if an object has a given property directly on // itself (in other words, not on a prototype). Unlike the internal `has` // function, this public version can also traverse nested properties. export default function has(obj, path) { path = toPath(path); var length = path.length; for (var i = 0; i < length; i++) { var key = path[i]; if (!_has(obj, key)) return false; obj = obj[key]; } return !!length; } ================================================ FILE: modules/identity.js ================================================ // Keep the identity function around for default iteratees. export default function identity(value) { return value; } ================================================ FILE: modules/index-all.js ================================================ // ESM Exports // =========== // This module is the package entry point for ES module users. In other words, // it is the module they are interfacing with when they import from the whole // package instead of from a submodule, like this: // // ```js // import { map } from 'underscore'; // ``` // // The difference with `./index-default`, which is the package entry point for // CommonJS, AMD and UMD users, is purely technical. In ES modules, named and // default exports are considered to be siblings, so when you have a default // export, its properties are not automatically available as named exports. For // this reason, we re-export the named exports in addition to providing the same // default export as in `./index-default`. export { default } from './index-default.js'; export * from './index.js'; ================================================ FILE: modules/index-default.js ================================================ // Default Export // ============== // In this module, we mix our bundled exports into the `_` object and export // the result. This is analogous to setting `module.exports = _` in CommonJS. // Hence, this module is also the entry point of our UMD bundle and the package // entry point for CommonJS and AMD users. In other words, this is (the source // of) the module you are interfacing with when you do any of the following: // // ```js // // CommonJS // var _ = require('underscore'); // // // AMD // define(['underscore'], function(_) {...}); // // // UMD in the browser // // _ is available as a global variable // ``` import * as allExports from './index.js'; import { mixin } from './index.js'; // Add all of the Underscore functions to the wrapper object. var _ = mixin(allExports); // Legacy Node.js API. _._ = _; // Export the Underscore API. export default _; ================================================ FILE: modules/index.js ================================================ // Named Exports // ============= // Underscore.js 1.13.8 // https://underscorejs.org // (c) 2009-2026 Jeremy Ashkenas, Julian Gonggrijp, and DocumentCloud and Investigative Reporters & Editors // Underscore may be freely distributed under the MIT license. // Baseline setup. export { VERSION } from './_setup.js'; export { default as restArguments } from './restArguments.js'; // Object Functions // ---------------- // Our most fundamental functions operate on any JavaScript object. // Most functions in Underscore depend on at least one function in this section. // A group of functions that check the types of core JavaScript values. // These are often informally referred to as the "isType" functions. export { default as isObject } from './isObject.js'; export { default as isNull } from './isNull.js'; export { default as isUndefined } from './isUndefined.js'; export { default as isBoolean } from './isBoolean.js'; export { default as isElement } from './isElement.js'; export { default as isString } from './isString.js'; export { default as isNumber } from './isNumber.js'; export { default as isDate } from './isDate.js'; export { default as isRegExp } from './isRegExp.js'; export { default as isError } from './isError.js'; export { default as isSymbol } from './isSymbol.js'; export { default as isArrayBuffer } from './isArrayBuffer.js'; export { default as isDataView } from './isDataView.js'; export { default as isArray } from './isArray.js'; export { default as isFunction } from './isFunction.js'; export { default as isArguments } from './isArguments.js'; export { default as isFinite } from './isFinite.js'; export { default as isNaN } from './isNaN.js'; export { default as isTypedArray } from './isTypedArray.js'; export { default as isEmpty } from './isEmpty.js'; export { default as isMatch } from './isMatch.js'; export { default as isEqual } from './isEqual.js'; export { default as isMap } from './isMap.js'; export { default as isWeakMap } from './isWeakMap.js'; export { default as isSet } from './isSet.js'; export { default as isWeakSet } from './isWeakSet.js'; // Functions that treat an object as a dictionary of key-value pairs. export { default as keys } from './keys.js'; export { default as allKeys } from './allKeys.js'; export { default as values } from './values.js'; export { default as pairs } from './pairs.js'; export { default as invert } from './invert.js'; export { default as functions, default as methods } from './functions.js'; export { default as extend } from './extend.js'; export { default as extendOwn, default as assign } from './extendOwn.js'; export { default as defaults } from './defaults.js'; export { default as create } from './create.js'; export { default as clone } from './clone.js'; export { default as tap } from './tap.js'; export { default as get } from './get.js'; export { default as has } from './has.js'; export { default as mapObject } from './mapObject.js'; // Utility Functions // ----------------- // A bit of a grab bag: Predicate-generating functions for use with filters and // loops, string escaping and templating, create random numbers and unique ids, // and functions that facilitate Underscore's chaining and iteration conventions. export { default as identity } from './identity.js'; export { default as constant } from './constant.js'; export { default as noop } from './noop.js'; export { default as toPath } from './toPath.js'; export { default as property } from './property.js'; export { default as propertyOf } from './propertyOf.js'; export { default as matcher, default as matches } from './matcher.js'; export { default as times } from './times.js'; export { default as random } from './random.js'; export { default as now } from './now.js'; export { default as escape } from './escape.js'; export { default as unescape } from './unescape.js'; export { default as templateSettings } from './templateSettings.js'; export { default as template } from './template.js'; export { default as result } from './result.js'; export { default as uniqueId } from './uniqueId.js'; export { default as chain } from './chain.js'; export { default as iteratee } from './iteratee.js'; // Function (ahem) Functions // ------------------------- // These functions take a function as an argument and return a new function // as the result. Also known as higher-order functions. export { default as partial } from './partial.js'; export { default as bind } from './bind.js'; export { default as bindAll } from './bindAll.js'; export { default as memoize } from './memoize.js'; export { default as delay } from './delay.js'; export { default as defer } from './defer.js'; export { default as throttle } from './throttle.js'; export { default as debounce } from './debounce.js'; export { default as wrap } from './wrap.js'; export { default as negate } from './negate.js'; export { default as compose } from './compose.js'; export { default as after } from './after.js'; export { default as before } from './before.js'; export { default as once } from './once.js'; // Finders // ------- // Functions that extract (the position of) a single element from an object // or array based on some criterion. export { default as findKey } from './findKey.js'; export { default as findIndex } from './findIndex.js'; export { default as findLastIndex } from './findLastIndex.js'; export { default as sortedIndex } from './sortedIndex.js'; export { default as indexOf } from './indexOf.js'; export { default as lastIndexOf } from './lastIndexOf.js'; export { default as find, default as detect } from './find.js'; export { default as findWhere } from './findWhere.js'; // Collection Functions // -------------------- // Functions that work on any collection of elements: either an array, or // an object of key-value pairs. export { default as each, default as forEach } from './each.js'; export { default as map, default as collect } from './map.js'; export { default as reduce, default as foldl, default as inject } from './reduce.js'; export { default as reduceRight, default as foldr } from './reduceRight.js'; export { default as filter, default as select } from './filter.js'; export { default as reject } from './reject.js'; export { default as every, default as all } from './every.js'; export { default as some, default as any } from './some.js'; export { default as contains, default as includes, default as include } from './contains.js'; export { default as invoke } from './invoke.js'; export { default as pluck } from './pluck.js'; export { default as where } from './where.js'; export { default as max } from './max.js'; export { default as min } from './min.js'; export { default as shuffle } from './shuffle.js'; export { default as sample } from './sample.js'; export { default as sortBy } from './sortBy.js'; export { default as groupBy } from './groupBy.js'; export { default as indexBy } from './indexBy.js'; export { default as countBy } from './countBy.js'; export { default as partition } from './partition.js'; export { default as toArray } from './toArray.js'; export { default as size } from './size.js'; // `_.pick` and `_.omit` are actually object functions, but we put // them here in order to create a more natural reading order in the // monolithic build as they depend on `_.contains`. export { default as pick } from './pick.js'; export { default as omit } from './omit.js'; // Array Functions // --------------- // Functions that operate on arrays (and array-likes) only, because they’re // expressed in terms of operations on an ordered list of values. export { default as first, default as head, default as take } from './first.js'; export { default as initial } from './initial.js'; export { default as last } from './last.js'; export { default as rest, default as tail, default as drop } from './rest.js'; export { default as compact } from './compact.js'; export { default as flatten } from './flatten.js'; export { default as without } from './without.js'; export { default as uniq, default as unique } from './uniq.js'; export { default as union } from './union.js'; export { default as intersection } from './intersection.js'; export { default as difference } from './difference.js'; export { default as unzip, default as transpose } from './unzip.js'; export { default as zip } from './zip.js'; export { default as object } from './object.js'; export { default as range } from './range.js'; export { default as chunk } from './chunk.js'; // OOP // --- // These modules support the "object-oriented" calling style. See also // `underscore.js` and `index-default.js`. export { default as mixin } from './mixin.js'; export { default } from './underscore-array-methods.js'; ================================================ FILE: modules/indexBy.js ================================================ import group from './_group.js'; // Indexes the object's values by a criterion, similar to `_.groupBy`, but for // when you know that your index values will be unique. export default group(function(result, value, key) { result[key] = value; }); ================================================ FILE: modules/indexOf.js ================================================ import sortedIndex from './sortedIndex.js'; import findIndex from './findIndex.js'; import createIndexFinder from './_createIndexFinder.js'; // Return the position of the first occurrence of an item in an array, // or -1 if the item is not included in the array. // If the array is large and already in sort order, pass `true` // for **isSorted** to use binary search. export default createIndexFinder(1, findIndex, sortedIndex); ================================================ FILE: modules/initial.js ================================================ import { slice } from './_setup.js'; // Returns everything but the last entry of the array. Especially useful on // the arguments object. Passing **n** will return all the values in // the array, excluding the last N. export default function initial(array, n, guard) { return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n))); } ================================================ FILE: modules/intersection.js ================================================ import getLength from './_getLength.js'; import contains from './contains.js'; // Produce an array that contains every item shared between all the // passed-in arrays. export default function intersection(array) { var result = []; var argsLength = arguments.length; for (var i = 0, length = getLength(array); i < length; i++) { var item = array[i]; if (contains(result, item)) continue; var j; for (j = 1; j < argsLength; j++) { if (!contains(arguments[j], item)) break; } if (j === argsLength) result.push(item); } return result; } ================================================ FILE: modules/invert.js ================================================ import keys from './keys.js'; // Invert the keys and values of an object. The values must be serializable. export default function invert(obj) { var result = {}; var _keys = keys(obj); for (var i = 0, length = _keys.length; i < length; i++) { result[obj[_keys[i]]] = _keys[i]; } return result; } ================================================ FILE: modules/invoke.js ================================================ import restArguments from './restArguments.js'; import isFunction from './isFunction.js'; import map from './map.js'; import deepGet from './_deepGet.js'; import toPath from './_toPath.js'; // Invoke a method (with arguments) on every item in a collection. export default restArguments(function(obj, path, args) { var contextPath, func; if (isFunction(path)) { func = path; } else { path = toPath(path); contextPath = path.slice(0, -1); path = path[path.length - 1]; } return map(obj, function(context) { var method = func; if (!method) { if (contextPath && contextPath.length) { context = deepGet(context, contextPath); } if (context == null) return void 0; method = context[path]; } return method == null ? method : method.apply(context, args); }); }); ================================================ FILE: modules/isArguments.js ================================================ import tagTester from './_tagTester.js'; import has from './_has.js'; var isArguments = tagTester('Arguments'); // Define a fallback version of the method in browsers (ahem, IE < 9), where // there isn't any inspectable "Arguments" type. (function() { if (!isArguments(arguments)) { isArguments = function(obj) { return has(obj, 'callee'); }; } }()); export default isArguments; ================================================ FILE: modules/isArray.js ================================================ import { nativeIsArray } from './_setup.js'; import tagTester from './_tagTester.js'; // Is a given value an array? // Delegates to ECMA5's native `Array.isArray`. export default nativeIsArray || tagTester('Array'); ================================================ FILE: modules/isArrayBuffer.js ================================================ import tagTester from './_tagTester.js'; export default tagTester('ArrayBuffer'); ================================================ FILE: modules/isBoolean.js ================================================ import { toString } from './_setup.js'; // Is a given value a boolean? export default function isBoolean(obj) { return obj === true || obj === false || toString.call(obj) === '[object Boolean]'; } ================================================ FILE: modules/isDataView.js ================================================ import tagTester from './_tagTester.js'; import isFunction from './isFunction.js'; import isArrayBuffer from './isArrayBuffer.js'; import { hasDataViewBug } from './_stringTagBug.js'; var isDataView = tagTester('DataView'); // In IE 10 - Edge 13, we need a different heuristic // to determine whether an object is a `DataView`. // Also, in cases where the native `DataView` is // overridden we can't rely on the tag itself. function alternateIsDataView(obj) { return obj != null && isFunction(obj.getInt8) && isArrayBuffer(obj.buffer); } export default (hasDataViewBug ? alternateIsDataView : isDataView); ================================================ FILE: modules/isDate.js ================================================ import tagTester from './_tagTester.js'; export default tagTester('Date'); ================================================ FILE: modules/isElement.js ================================================ // Is a given value a DOM element? export default function isElement(obj) { return !!(obj && obj.nodeType === 1); } ================================================ FILE: modules/isEmpty.js ================================================ import getLength from './_getLength.js'; import isArray from './isArray.js'; import isString from './isString.js'; import isArguments from './isArguments.js'; import keys from './keys.js'; // Is a given array, string, or object empty? // An "empty" object has no enumerable own-properties. export default function isEmpty(obj) { if (obj == null) return true; // Skip the more expensive `toString`-based type checks if `obj` has no // `.length`. var length = getLength(obj); if (typeof length == 'number' && ( isArray(obj) || isString(obj) || isArguments(obj) )) return length === 0; return getLength(keys(obj)) === 0; } ================================================ FILE: modules/isEqual.js ================================================ import _ from './underscore.js'; import { toString, SymbolProto } from './_setup.js'; import getByteLength from './_getByteLength.js'; import isTypedArray from './isTypedArray.js'; import isFunction from './isFunction.js'; import { hasDataViewBug } from './_stringTagBug.js'; import isDataView from './isDataView.js'; import keys from './keys.js'; import has from './_has.js'; import toBufferView from './_toBufferView.js'; // We use this string twice, so give it a name for minification. var tagDataView = '[object DataView]'; // Perform a deep comparison to check if two objects are equal. export default function isEqual(a, b) { // Keep track of which pairs of values need to be compared. We will be // trampolining on this stack instead of using function recursion. // (CVE-2026-27601) var todo = [{a: a, b: b}]; // Initializing stacks of traversed objects for cycle detection. var aStack = [], bStack = []; // Keep traversing pairs until there is nothing left to compare. while (todo.length) { var frame = todo.pop(); // As a special case, a single `true` on the todo means that we can // unwind the cycle detection stacks. if (frame === true) { // Remove the first object from the stack of traversed objects. aStack.pop(); bStack.pop(); continue; } a = frame.a; b = frame.b; // Identical objects are equal. `0 === -0`, but they aren't identical. // See the [Harmony `egal` proposal](https://wiki.ecmascript.org/doku.php?id=harmony:egal). if (a === b) { if (a !== 0 || 1 / a === 1 / b) continue; return false; } // `null` or `undefined` only equal to itself (strict comparison). if (a == null || b == null) return false; // `NaN`s are equivalent, but non-reflexive. if (a !== a) { if (b !== b) continue; return false; } // Exhaust primitive checks var type = typeof a; if (type !== 'function' && type !== 'object' && typeof b != 'object') return false; // Unwrap any wrapped objects. if (a instanceof _) a = a._wrapped; if (b instanceof _) b = b._wrapped; // Compare `[[Class]]` names. var className = toString.call(a); if (className !== toString.call(b)) return false; // Work around a bug in IE 10 - Edge 13. if (hasDataViewBug && className == '[object Object]' && isDataView(a)) { if (!isDataView(b)) return false; className = tagDataView; } switch (className) { // These types are compared by value. case '[object RegExp]': // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i') case '[object String]': // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is // equivalent to `new String("5")`. if ('' + a === '' + b) continue; return false; case '[object Number]': todo.push({a: +a, b: +b}); continue; case '[object Date]': case '[object Boolean]': // Coerce dates and booleans to numeric primitive values. Dates are compared by their // millisecond representations. Note that invalid dates with millisecond representations // of `NaN` are not equivalent. if (+a === +b) continue; return false; case '[object Symbol]': if (SymbolProto.valueOf.call(a) === SymbolProto.valueOf.call(b)) continue; return false; case '[object ArrayBuffer]': case tagDataView: // Coerce to typed array so we can fall through. todo.push({a: toBufferView(a), b: toBufferView(b)}); continue; } var areArrays = className === '[object Array]'; if (!areArrays && isTypedArray(a)) { var byteLength = getByteLength(a); if (byteLength !== getByteLength(b)) return false; if (a.buffer === b.buffer && a.byteOffset === b.byteOffset) continue; areArrays = true; } if (!areArrays) { if (typeof a != 'object' || typeof b != 'object') return false; // Objects with different constructors are not equivalent, but `Object`s or `Array`s // from different frames are. var aCtor = a.constructor, bCtor = b.constructor; if (aCtor !== bCtor && !(isFunction(aCtor) && aCtor instanceof aCtor && isFunction(bCtor) && bCtor instanceof bCtor) && ('constructor' in a && 'constructor' in b)) { return false; } } // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. var length = aStack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. if (aStack[length] === a) { // Cycle detected. Break out of the inner loop and continue the outer // loop. Step 1: if (bStack[length] === b) break; return false; } } // Step 2, use `length` to verify whether we detected a cycle: if (length >= 0) continue; // Add the first object to the stack of traversed objects. aStack.push(a); bStack.push(b); // Remember to remove them again after the recursion below. todo.push(true); // Recursively compare objects and arrays. if (areArrays) { // Compare array lengths to determine if a deep comparison is necessary. length = a.length; if (length !== b.length) return false; // Deep compare the contents, ignoring non-numeric properties. while (length--) { todo.push({a: a[length], b: b[length]}); } } else { // Deep compare objects. var _keys = keys(a), key; length = _keys.length; // Ensure that both objects contain the same number of properties before comparing deep equality. if (keys(b).length !== length) return false; while (length--) { // Deep compare each member key = _keys[length]; if (!has(b, key)) return false; todo.push({a: a[key], b: b[key]}); } } } // We made it to the end and found no differences. return true; } ================================================ FILE: modules/isError.js ================================================ import tagTester from './_tagTester.js'; export default tagTester('Error'); ================================================ FILE: modules/isFinite.js ================================================ import { _isFinite } from './_setup.js'; import isSymbol from './isSymbol.js'; // Is a given object a finite number? export default function isFinite(obj) { return !isSymbol(obj) && _isFinite(obj) && !isNaN(parseFloat(obj)); } ================================================ FILE: modules/isFunction.js ================================================ import tagTester from './_tagTester.js'; import { root } from './_setup.js'; var isFunction = tagTester('Function'); // Optimize `isFunction` if appropriate. Work around some `typeof` bugs in old // v8, IE 11 (#1621), Safari 8 (#1929), and PhantomJS (#2236). var nodelist = root.document && root.document.childNodes; if (typeof /./ != 'function' && typeof Int8Array != 'object' && typeof nodelist != 'function') { isFunction = function(obj) { return typeof obj == 'function' || false; }; } export default isFunction; ================================================ FILE: modules/isMap.js ================================================ import tagTester from './_tagTester.js'; import { isIE11 } from './_stringTagBug.js'; import { ie11fingerprint, mapMethods } from './_methodFingerprint.js'; export default isIE11 ? ie11fingerprint(mapMethods) : tagTester('Map'); ================================================ FILE: modules/isMatch.js ================================================ import keys from './keys.js'; // Returns whether an object has a given set of `key:value` pairs. export default function isMatch(object, attrs) { var _keys = keys(attrs), length = _keys.length; if (object == null) return !length; var obj = Object(object); for (var i = 0; i < length; i++) { var key = _keys[i]; if (attrs[key] !== obj[key] || !(key in obj)) return false; } return true; } ================================================ FILE: modules/isNaN.js ================================================ import { _isNaN } from './_setup.js'; import isNumber from './isNumber.js'; // Is the given value `NaN`? export default function isNaN(obj) { return isNumber(obj) && _isNaN(obj); } ================================================ FILE: modules/isNull.js ================================================ // Is a given value equal to null? export default function isNull(obj) { return obj === null; } ================================================ FILE: modules/isNumber.js ================================================ import tagTester from './_tagTester.js'; export default tagTester('Number'); ================================================ FILE: modules/isObject.js ================================================ // Is a given variable an object? export default function isObject(obj) { var type = typeof obj; return type === 'function' || (type === 'object' && !!obj); } ================================================ FILE: modules/isRegExp.js ================================================ import tagTester from './_tagTester.js'; export default tagTester('RegExp'); ================================================ FILE: modules/isSet.js ================================================ import tagTester from './_tagTester.js'; import { isIE11 } from './_stringTagBug.js'; import { ie11fingerprint, setMethods } from './_methodFingerprint.js'; export default isIE11 ? ie11fingerprint(setMethods) : tagTester('Set'); ================================================ FILE: modules/isString.js ================================================ import tagTester from './_tagTester.js'; export default tagTester('String'); ================================================ FILE: modules/isSymbol.js ================================================ import tagTester from './_tagTester.js'; export default tagTester('Symbol'); ================================================ FILE: modules/isTypedArray.js ================================================ import { supportsArrayBuffer, nativeIsView, toString } from './_setup.js'; import isDataView from './isDataView.js'; import constant from './constant.js'; import isBufferLike from './_isBufferLike.js'; // Is a given value a typed array? var typedArrayPattern = /\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/; function isTypedArray(obj) { // `ArrayBuffer.isView` is the most future-proof, so use it when available. // Otherwise, fall back on the above regular expression. return nativeIsView ? (nativeIsView(obj) && !isDataView(obj)) : isBufferLike(obj) && typedArrayPattern.test(toString.call(obj)); } export default supportsArrayBuffer ? isTypedArray : constant(false); ================================================ FILE: modules/isUndefined.js ================================================ // Is a given variable undefined? export default function isUndefined(obj) { return obj === void 0; } ================================================ FILE: modules/isWeakMap.js ================================================ import tagTester from './_tagTester.js'; import { isIE11 } from './_stringTagBug.js'; import { ie11fingerprint, weakMapMethods } from './_methodFingerprint.js'; export default isIE11 ? ie11fingerprint(weakMapMethods) : tagTester('WeakMap'); ================================================ FILE: modules/isWeakSet.js ================================================ import tagTester from './_tagTester.js'; export default tagTester('WeakSet'); ================================================ FILE: modules/iteratee.js ================================================ import _ from './underscore.js'; import baseIteratee from './_baseIteratee.js'; // External wrapper for our callback generator. Users may customize // `_.iteratee` if they want additional predicate/iteratee shorthand styles. // This abstraction hides the internal-only `argCount` argument. export default function iteratee(value, context) { return baseIteratee(value, context, Infinity); } _.iteratee = iteratee; ================================================ FILE: modules/keys.js ================================================ import isObject from './isObject.js'; import { nativeKeys, hasEnumBug } from './_setup.js'; import has from './_has.js'; import collectNonEnumProps from './_collectNonEnumProps.js'; // Retrieve the names of an object's own properties. // Delegates to **ECMAScript 5**'s native `Object.keys`. export default function keys(obj) { if (!isObject(obj)) return []; if (nativeKeys) return nativeKeys(obj); var keys = []; for (var key in obj) if (has(obj, key)) keys.push(key); // Ahem, IE < 9. if (hasEnumBug) collectNonEnumProps(obj, keys); return keys; } ================================================ FILE: modules/last.js ================================================ import rest from './rest.js'; // Get the last element of an array. Passing **n** will return the last N // values in the array. export default function last(array, n, guard) { if (array == null || array.length < 1) return n == null || guard ? void 0 : []; if (n == null || guard) return array[array.length - 1]; return rest(array, Math.max(0, array.length - n)); } ================================================ FILE: modules/lastIndexOf.js ================================================ import findLastIndex from './findLastIndex.js'; import createIndexFinder from './_createIndexFinder.js'; // Return the position of the last occurrence of an item in an array, // or -1 if the item is not included in the array. export default createIndexFinder(-1, findLastIndex); ================================================ FILE: modules/map.js ================================================ import cb from './_cb.js'; import isArrayLike from './_isArrayLike.js'; import keys from './keys.js'; // Return the results of applying the iteratee to each element. export default function map(obj, iteratee, context) { iteratee = cb(iteratee, context); var _keys = !isArrayLike(obj) && keys(obj), length = (_keys || obj).length, results = Array(length); for (var index = 0; index < length; index++) { var currentKey = _keys ? _keys[index] : index; results[index] = iteratee(obj[currentKey], currentKey, obj); } return results; } ================================================ FILE: modules/mapObject.js ================================================ import cb from './_cb.js'; import keys from './keys.js'; // Returns the results of applying the `iteratee` to each element of `obj`. // In contrast to `_.map` it returns an object. export default function mapObject(obj, iteratee, context) { iteratee = cb(iteratee, context); var _keys = keys(obj), length = _keys.length, results = {}; for (var index = 0; index < length; index++) { var currentKey = _keys[index]; results[currentKey] = iteratee(obj[currentKey], currentKey, obj); } return results; } ================================================ FILE: modules/matcher.js ================================================ import extendOwn from './extendOwn.js'; import isMatch from './isMatch.js'; // Returns a predicate for checking whether an object has a given set of // `key:value` pairs. export default function matcher(attrs) { attrs = extendOwn({}, attrs); return function(obj) { return isMatch(obj, attrs); }; } ================================================ FILE: modules/max.js ================================================ import isArrayLike from './_isArrayLike.js'; import values from './values.js'; import cb from './_cb.js'; import each from './each.js'; // Return the maximum element (or element-based computation). export default function max(obj, iteratee, context) { var result = -Infinity, lastComputed = -Infinity, value, computed; if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null)) { obj = isArrayLike(obj) ? obj : values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value != null && value > result) { result = value; } } } else { iteratee = cb(iteratee, context); each(obj, function(v, index, list) { computed = iteratee(v, index, list); if (computed > lastComputed || (computed === -Infinity && result === -Infinity)) { result = v; lastComputed = computed; } }); } return result; } ================================================ FILE: modules/memoize.js ================================================ import has from './_has.js'; // Memoize an expensive function by storing its results. export default function memoize(func, hasher) { var memoize = function(key) { var cache = memoize.cache; var address = '' + (hasher ? hasher.apply(this, arguments) : key); if (!has(cache, address)) cache[address] = func.apply(this, arguments); return cache[address]; }; memoize.cache = {}; return memoize; } ================================================ FILE: modules/min.js ================================================ import isArrayLike from './_isArrayLike.js'; import values from './values.js'; import cb from './_cb.js'; import each from './each.js'; // Return the minimum element (or element-based computation). export default function min(obj, iteratee, context) { var result = Infinity, lastComputed = Infinity, value, computed; if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null)) { obj = isArrayLike(obj) ? obj : values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value != null && value < result) { result = value; } } } else { iteratee = cb(iteratee, context); each(obj, function(v, index, list) { computed = iteratee(v, index, list); if (computed < lastComputed || (computed === Infinity && result === Infinity)) { result = v; lastComputed = computed; } }); } return result; } ================================================ FILE: modules/mixin.js ================================================ import _ from './underscore.js'; import each from './each.js'; import functions from './functions.js'; import { push } from './_setup.js'; import chainResult from './_chainResult.js'; // Add your own custom functions to the Underscore object. export default function mixin(obj) { each(functions(obj), function(name) { var func = _[name] = obj[name]; _.prototype[name] = function() { var args = [this._wrapped]; push.apply(args, arguments); return chainResult(this, func.apply(_, args)); }; }); return _; } ================================================ FILE: modules/negate.js ================================================ // Returns a negated version of the passed-in predicate. export default function negate(predicate) { return function() { return !predicate.apply(this, arguments); }; } ================================================ FILE: modules/noop.js ================================================ // Predicate-generating function. Often useful outside of Underscore. export default function noop(){} ================================================ FILE: modules/now.js ================================================ // A (possibly faster) way to get the current timestamp as an integer. export default Date.now || function() { return new Date().getTime(); }; ================================================ FILE: modules/object.js ================================================ import getLength from './_getLength.js'; // Converts lists into objects. Pass either a single array of `[key, value]` // pairs, or two parallel arrays of the same length -- one of keys, and one of // the corresponding values. Passing by pairs is the reverse of `_.pairs`. export default function object(list, values) { var result = {}; for (var i = 0, length = getLength(list); i < length; i++) { if (values) { result[list[i]] = values[i]; } else { result[list[i][0]] = list[i][1]; } } return result; } ================================================ FILE: modules/omit.js ================================================ import restArguments from './restArguments.js'; import isFunction from './isFunction.js'; import negate from './negate.js'; import map from './map.js'; import flatten from './_flatten.js'; import contains from './contains.js'; import pick from './pick.js'; // Return a copy of the object without the disallowed properties. export default restArguments(function(obj, keys) { var iteratee = keys[0], context; if (isFunction(iteratee)) { iteratee = negate(iteratee); if (keys.length > 1) context = keys[1]; } else { keys = map(flatten(keys, false, false), String); iteratee = function(value, key) { return !contains(keys, key); }; } return pick(obj, iteratee, context); }); ================================================ FILE: modules/once.js ================================================ import partial from './partial.js'; import before from './before.js'; // Returns a function that will be executed at most one time, no matter how // often you call it. Useful for lazy initialization. export default partial(before, 2); ================================================ FILE: modules/package.json ================================================ {"type":"module","version":"1.13.8"} ================================================ FILE: modules/pairs.js ================================================ import keys from './keys.js'; // Convert an object into a list of `[key, value]` pairs. // The opposite of `_.object` with one argument. export default function pairs(obj) { var _keys = keys(obj); var length = _keys.length; var pairs = Array(length); for (var i = 0; i < length; i++) { pairs[i] = [_keys[i], obj[_keys[i]]]; } return pairs; } ================================================ FILE: modules/partial.js ================================================ import restArguments from './restArguments.js'; import executeBound from './_executeBound.js'; import _ from './underscore.js'; // Partially apply a function by creating a version that has had some of its // arguments pre-filled, without changing its dynamic `this` context. `_` acts // as a placeholder by default, allowing any combination of arguments to be // pre-filled. Set `_.partial.placeholder` for a custom placeholder argument. var partial = restArguments(function(func, boundArgs) { var placeholder = partial.placeholder; var bound = function() { var position = 0, length = boundArgs.length; var args = Array(length); for (var i = 0; i < length; i++) { args[i] = boundArgs[i] === placeholder ? arguments[position++] : boundArgs[i]; } while (position < arguments.length) args.push(arguments[position++]); return executeBound(func, bound, this, this, args); }; return bound; }); partial.placeholder = _; export default partial; ================================================ FILE: modules/partition.js ================================================ import group from './_group.js'; // Split a collection into two arrays: one whose elements all pass the given // truth test, and one whose elements all do not pass the truth test. export default group(function(result, value, pass) { result[pass ? 0 : 1].push(value); }, true); ================================================ FILE: modules/pick.js ================================================ import restArguments from './restArguments.js'; import isFunction from './isFunction.js'; import optimizeCb from './_optimizeCb.js'; import allKeys from './allKeys.js'; import keyInObj from './_keyInObj.js'; import flatten from './_flatten.js'; // Return a copy of the object only containing the allowed properties. export default restArguments(function(obj, keys) { var result = {}, iteratee = keys[0]; if (obj == null) return result; if (isFunction(iteratee)) { if (keys.length > 1) iteratee = optimizeCb(iteratee, keys[1]); keys = allKeys(obj); } else { iteratee = keyInObj; keys = flatten(keys, false, false); obj = Object(obj); } for (var i = 0, length = keys.length; i < length; i++) { var key = keys[i]; var value = obj[key]; if (iteratee(value, key, obj)) result[key] = value; } return result; }); ================================================ FILE: modules/pluck.js ================================================ import map from './map.js'; import property from './property.js'; // Convenience version of a common use case of `_.map`: fetching a property. export default function pluck(obj, key) { return map(obj, property(key)); } ================================================ FILE: modules/property.js ================================================ import deepGet from './_deepGet.js'; import toPath from './_toPath.js'; // Creates a function that, when passed an object, will traverse that object’s // properties down the given `path`, specified as an array of keys or indices. export default function property(path) { path = toPath(path); return function(obj) { return deepGet(obj, path); }; } ================================================ FILE: modules/propertyOf.js ================================================ import noop from './noop.js'; import get from './get.js'; // Generates a function for a given object that returns a given property. export default function propertyOf(obj) { if (obj == null) return noop; return function(path) { return get(obj, path); }; } ================================================ FILE: modules/random.js ================================================ // Return a random integer between `min` and `max` (inclusive). export default function random(min, max) { if (max == null) { max = min; min = 0; } return min + Math.floor(Math.random() * (max - min + 1)); } ================================================ FILE: modules/range.js ================================================ // Generate an integer Array containing an arithmetic progression. A port of // the native Python `range()` function. See // [the Python documentation](https://docs.python.org/library/functions.html#range). export default function range(start, stop, step) { if (stop == null) { stop = start || 0; start = 0; } if (!step) { step = stop < start ? -1 : 1; } var length = Math.max(Math.ceil((stop - start) / step), 0); var range = Array(length); for (var idx = 0; idx < length; idx++, start += step) { range[idx] = start; } return range; } ================================================ FILE: modules/reduce.js ================================================ import createReduce from './_createReduce.js'; // **Reduce** builds up a single result from a list of values, aka `inject`, // or `foldl`. export default createReduce(1); ================================================ FILE: modules/reduceRight.js ================================================ import createReduce from './_createReduce.js'; // The right-associative version of reduce, also known as `foldr`. export default createReduce(-1); ================================================ FILE: modules/reject.js ================================================ import filter from './filter.js'; import negate from './negate.js'; import cb from './_cb.js'; // Return all the elements for which a truth test fails. export default function reject(obj, predicate, context) { return filter(obj, negate(cb(predicate)), context); } ================================================ FILE: modules/rest.js ================================================ import { slice } from './_setup.js'; // Returns everything but the first entry of the `array`. Especially useful on // the `arguments` object. Passing an **n** will return the rest N values in the // `array`. export default function rest(array, n, guard) { return slice.call(array, n == null || guard ? 1 : n); } ================================================ FILE: modules/restArguments.js ================================================ // Some functions take a variable number of arguments, or a few expected // arguments at the beginning and then a variable number of values to operate // on. This helper accumulates all remaining arguments past the function’s // argument length (or an explicit `startIndex`), into an array that becomes // the last argument. Similar to ES6’s "rest parameter". export default function restArguments(func, startIndex) { startIndex = startIndex == null ? func.length - 1 : +startIndex; return function() { var length = Math.max(arguments.length - startIndex, 0), rest = Array(length), index = 0; for (; index < length; index++) { rest[index] = arguments[index + startIndex]; } switch (startIndex) { case 0: return func.call(this, rest); case 1: return func.call(this, arguments[0], rest); case 2: return func.call(this, arguments[0], arguments[1], rest); } var args = Array(startIndex + 1); for (index = 0; index < startIndex; index++) { args[index] = arguments[index]; } args[startIndex] = rest; return func.apply(this, args); }; } ================================================ FILE: modules/result.js ================================================ import isFunction from './isFunction.js'; import toPath from './_toPath.js'; // Traverses the children of `obj` along `path`. If a child is a function, it // is invoked with its parent as context. Returns the value of the final // child, or `fallback` if any child is undefined. export default function result(obj, path, fallback) { path = toPath(path); var length = path.length; if (!length) { return isFunction(fallback) ? fallback.call(obj) : fallback; } for (var i = 0; i < length; i++) { var prop = obj == null ? void 0 : obj[path[i]]; if (prop === void 0) { prop = fallback; i = length; // Ensure we don't continue iterating. } obj = isFunction(prop) ? prop.call(obj) : prop; } return obj; } ================================================ FILE: modules/sample.js ================================================ import isArrayLike from './_isArrayLike.js'; import values from './values.js'; import getLength from './_getLength.js'; import random from './random.js'; import toArray from './toArray.js'; // Sample **n** random values from a collection using the modern version of the // [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher–Yates_shuffle). // If **n** is not specified, returns a single random element. // The internal `guard` argument allows it to work with `_.map`. export default function sample(obj, n, guard) { if (n == null || guard) { if (!isArrayLike(obj)) obj = values(obj); return obj[random(obj.length - 1)]; } var sample = toArray(obj); var length = getLength(sample); n = Math.max(Math.min(n, length), 0); var last = length - 1; for (var index = 0; index < n; index++) { var rand = random(index, last); var temp = sample[index]; sample[index] = sample[rand]; sample[rand] = temp; } return sample.slice(0, n); } ================================================ FILE: modules/shuffle.js ================================================ import sample from './sample.js'; // Shuffle a collection. export default function shuffle(obj) { return sample(obj, Infinity); } ================================================ FILE: modules/size.js ================================================ import isArrayLike from './_isArrayLike.js'; import keys from './keys.js'; // Return the number of elements in a collection. export default function size(obj) { if (obj == null) return 0; return isArrayLike(obj) ? obj.length : keys(obj).length; } ================================================ FILE: modules/some.js ================================================ import cb from './_cb.js'; import isArrayLike from './_isArrayLike.js'; import keys from './keys.js'; // Determine if at least one element in the object passes a truth test. export default function some(obj, predicate, context) { predicate = cb(predicate, context); var _keys = !isArrayLike(obj) && keys(obj), length = (_keys || obj).length; for (var index = 0; index < length; index++) { var currentKey = _keys ? _keys[index] : index; if (predicate(obj[currentKey], currentKey, obj)) return true; } return false; } ================================================ FILE: modules/sortBy.js ================================================ import cb from './_cb.js'; import pluck from './pluck.js'; import map from './map.js'; // Sort the object's values by a criterion produced by an iteratee. export default function sortBy(obj, iteratee, context) { var index = 0; iteratee = cb(iteratee, context); return pluck(map(obj, function(value, key, list) { return { value: value, index: index++, criteria: iteratee(value, key, list) }; }).sort(function(left, right) { var a = left.criteria; var b = right.criteria; if (a !== b) { if (a > b || a === void 0) return 1; if (a < b || b === void 0) return -1; } return left.index - right.index; }), 'value'); } ================================================ FILE: modules/sortedIndex.js ================================================ import cb from './_cb.js'; import getLength from './_getLength.js'; // Use a comparator function to figure out the smallest index at which // an object should be inserted so as to maintain order. Uses binary search. export default function sortedIndex(array, obj, iteratee, context) { iteratee = cb(iteratee, context, 1); var value = iteratee(obj); var low = 0, high = getLength(array); while (low < high) { var mid = Math.floor((low + high) / 2); if (iteratee(array[mid]) < value) low = mid + 1; else high = mid; } return low; } ================================================ FILE: modules/tap.js ================================================ // Invokes `interceptor` with the `obj` and then returns `obj`. // The primary purpose of this method is to "tap into" a method chain, in // order to perform operations on intermediate results within the chain. export default function tap(obj, interceptor) { interceptor(obj); return obj; } ================================================ FILE: modules/template.js ================================================ import defaults from './defaults.js'; import _ from './underscore.js'; import './templateSettings.js'; // When customizing `_.templateSettings`, if you don't want to define an // interpolation, evaluation or escaping regex, we need one that is // guaranteed not to match. var noMatch = /(.)^/; // Certain characters need to be escaped so that they can be put into a // string literal. var escapes = { "'": "'", '\\': '\\', '\r': 'r', '\n': 'n', '\u2028': 'u2028', '\u2029': 'u2029' }; var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g; function escapeChar(match) { return '\\' + escapes[match]; } // In order to prevent third-party code injection through // `_.templateSettings.variable`, we test it against the following regular // expression. It is intentionally a bit more liberal than just matching valid // identifiers, but still prevents possible loopholes through defaults or // destructuring assignment. var bareIdentifier = /^\s*(\w|\$)+\s*$/; // JavaScript micro-templating, similar to John Resig's implementation. // Underscore templating handles arbitrary delimiters, preserves whitespace, // and correctly escapes quotes within interpolated code. // NB: `oldSettings` only exists for backwards compatibility. export default function template(text, settings, oldSettings) { if (!settings && oldSettings) settings = oldSettings; settings = defaults({}, settings, _.templateSettings); // Combine delimiters into one regular expression via alternation. var matcher = RegExp([ (settings.escape || noMatch).source, (settings.interpolate || noMatch).source, (settings.evaluate || noMatch).source ].join('|') + '|$', 'g'); // Compile the template source, escaping string literals appropriately. var index = 0; var source = "__p+='"; text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { source += text.slice(index, offset).replace(escapeRegExp, escapeChar); index = offset + match.length; if (escape) { source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; } else if (interpolate) { source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; } else if (evaluate) { source += "';\n" + evaluate + "\n__p+='"; } // Adobe VMs need the match returned to produce the correct offset. return match; }); source += "';\n"; var argument = settings.variable; if (argument) { // Insure against third-party code injection. (CVE-2021-23358) if (!bareIdentifier.test(argument)) throw new Error( 'variable is not a bare identifier: ' + argument ); } else { // If a variable is not specified, place data values in local scope. source = 'with(obj||{}){\n' + source + '}\n'; argument = 'obj'; } source = "var __t,__p='',__j=Array.prototype.join," + "print=function(){__p+=__j.call(arguments,'');};\n" + source + 'return __p;\n'; var render; try { render = new Function(argument, '_', source); } catch (e) { e.source = source; throw e; } var template = function(data) { return render.call(this, data, _); }; // Provide the compiled source as a convenience for precompilation. template.source = 'function(' + argument + '){\n' + source + '}'; return template; } ================================================ FILE: modules/templateSettings.js ================================================ import _ from './underscore.js'; // By default, Underscore uses ERB-style template delimiters. Change the // following template settings to use alternative delimiters. export default _.templateSettings = { evaluate: /<%([\s\S]+?)%>/g, interpolate: /<%=([\s\S]+?)%>/g, escape: /<%-([\s\S]+?)%>/g }; ================================================ FILE: modules/throttle.js ================================================ import now from './now.js'; // Returns a function, that, when invoked, will only be triggered at most once // during a given window of time. Normally, the throttled function will run // as much as it can, without ever going more than once per `wait` duration; // but if you'd like to disable the execution on the leading edge, pass // `{leading: false}`. To disable execution on the trailing edge, ditto. export default function throttle(func, wait, options) { var timeout, context, args, result; var previous = 0; if (!options) options = {}; var later = function() { previous = options.leading === false ? 0 : now(); timeout = null; result = func.apply(context, args); if (!timeout) context = args = null; }; var throttled = function() { var _now = now(); if (!previous && options.leading === false) previous = _now; var remaining = wait - (_now - previous); context = this; args = arguments; if (remaining <= 0 || remaining > wait) { if (timeout) { clearTimeout(timeout); timeout = null; } previous = _now; result = func.apply(context, args); if (!timeout) context = args = null; } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; throttled.cancel = function() { clearTimeout(timeout); previous = 0; timeout = context = args = null; }; return throttled; } ================================================ FILE: modules/times.js ================================================ import optimizeCb from './_optimizeCb.js'; // Run a function **n** times. export default function times(n, iteratee, context) { var accum = Array(Math.max(0, n)); iteratee = optimizeCb(iteratee, context, 1); for (var i = 0; i < n; i++) accum[i] = iteratee(i); return accum; } ================================================ FILE: modules/toArray.js ================================================ import isArray from './isArray.js'; import { slice } from './_setup.js'; import isString from './isString.js'; import isArrayLike from './_isArrayLike.js'; import map from './map.js'; import identity from './identity.js'; import values from './values.js'; // Safely create a real, live array from anything iterable. var reStrSymbol = /[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g; export default function toArray(obj) { if (!obj) return []; if (isArray(obj)) return slice.call(obj); if (isString(obj)) { // Keep surrogate pair characters together. return obj.match(reStrSymbol); } if (isArrayLike(obj)) return map(obj, identity); return values(obj); } ================================================ FILE: modules/toPath.js ================================================ import _ from './underscore.js'; import isArray from './isArray.js'; // Normalize a (deep) property `path` to array. // Like `_.iteratee`, this function can be customized. export default function toPath(path) { return isArray(path) ? path : [path]; } _.toPath = toPath; ================================================ FILE: modules/underscore-array-methods.js ================================================ import _ from './underscore.js'; import each from './each.js'; import { ArrayProto } from './_setup.js'; import chainResult from './_chainResult.js'; // Add all mutator `Array` functions to the wrapper. each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { var obj = this._wrapped; if (obj != null) { method.apply(obj, arguments); if ((name === 'shift' || name === 'splice') && obj.length === 0) { delete obj[0]; } } return chainResult(this, obj); }; }); // Add all accessor `Array` functions to the wrapper. each(['concat', 'join', 'slice'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { var obj = this._wrapped; if (obj != null) obj = method.apply(obj, arguments); return chainResult(this, obj); }; }); export default _; ================================================ FILE: modules/underscore.js ================================================ import { VERSION } from './_setup.js'; // If Underscore is called as a function, it returns a wrapped object that can // be used OO-style. This wrapper holds altered versions of all functions added // through `_.mixin`. Wrapped objects may be chained. export default function _(obj) { if (obj instanceof _) return obj; if (!(this instanceof _)) return new _(obj); this._wrapped = obj; } _.VERSION = VERSION; // Extracts the result from a wrapped and chained object. _.prototype.value = function() { return this._wrapped; }; // Provide unwrapping proxies for some methods used in engine operations // such as arithmetic and JSON stringification. _.prototype.valueOf = _.prototype.toJSON = _.prototype.value; _.prototype.toString = function() { return String(this._wrapped); }; ================================================ FILE: modules/unescape.js ================================================ import createEscaper from './_createEscaper.js'; import unescapeMap from './_unescapeMap.js'; // Function for unescaping strings from HTML interpolation. export default createEscaper(unescapeMap); ================================================ FILE: modules/union.js ================================================ import restArguments from './restArguments.js'; import uniq from './uniq.js'; import flatten from './_flatten.js'; // Produce an array that contains the union: each distinct element from all of // the passed-in arrays. export default restArguments(function(arrays) { return uniq(flatten(arrays, true, true)); }); ================================================ FILE: modules/uniq.js ================================================ import isBoolean from './isBoolean.js'; import cb from './_cb.js'; import getLength from './_getLength.js'; import contains from './contains.js'; // Produce a duplicate-free version of the array. If the array has already // been sorted, you have the option of using a faster algorithm. // The faster algorithm will not work with an iteratee if the iteratee // is not a one-to-one function, so providing an iteratee will disable // the faster algorithm. export default function uniq(array, isSorted, iteratee, context) { if (!isBoolean(isSorted)) { context = iteratee; iteratee = isSorted; isSorted = false; } if (iteratee != null) iteratee = cb(iteratee, context); var result = []; var seen = []; for (var i = 0, length = getLength(array); i < length; i++) { var value = array[i], computed = iteratee ? iteratee(value, i, array) : value; if (isSorted && !iteratee) { if (!i || seen !== computed) result.push(value); seen = computed; } else if (iteratee) { if (!contains(seen, computed)) { seen.push(computed); result.push(value); } } else if (!contains(result, value)) { result.push(value); } } return result; } ================================================ FILE: modules/uniqueId.js ================================================ // Generate a unique integer id (unique within the entire client session). // Useful for temporary DOM ids. var idCounter = 0; export default function uniqueId(prefix) { var id = ++idCounter + ''; return prefix ? prefix + id : id; } ================================================ FILE: modules/unzip.js ================================================ import max from './max.js'; import getLength from './_getLength.js'; import pluck from './pluck.js'; // Complement of zip. Unzip accepts an array of arrays and groups // each array's elements on shared indices. export default function unzip(array) { var length = (array && max(array, getLength).length) || 0; var result = Array(length); for (var index = 0; index < length; index++) { result[index] = pluck(array, index); } return result; } ================================================ FILE: modules/values.js ================================================ import keys from './keys.js'; // Retrieve the values of an object's properties. export default function values(obj) { var _keys = keys(obj); var length = _keys.length; var values = Array(length); for (var i = 0; i < length; i++) { values[i] = obj[_keys[i]]; } return values; } ================================================ FILE: modules/where.js ================================================ import filter from './filter.js'; import matcher from './matcher.js'; // Convenience version of a common use case of `_.filter`: selecting only // objects containing specific `key:value` pairs. export default function where(obj, attrs) { return filter(obj, matcher(attrs)); } ================================================ FILE: modules/without.js ================================================ import restArguments from './restArguments.js'; import difference from './difference.js'; // Return a version of the array that does not contain the specified value(s). export default restArguments(function(array, otherArrays) { return difference(array, otherArrays); }); ================================================ FILE: modules/wrap.js ================================================ import partial from './partial.js'; // Returns the first function passed as an argument to the second, // allowing you to adjust arguments, run code before and after, and // conditionally execute the original function. export default function wrap(func, wrapper) { return partial(wrapper, func); } ================================================ FILE: modules/zip.js ================================================ import restArguments from './restArguments.js'; import unzip from './unzip.js'; // Zip together multiple lists into a single array -- elements that share // an index go together. export default restArguments(unzip); ================================================ FILE: package.json ================================================ { "name": "underscore", "description": "JavaScript's functional programming helper library.", "version": "1.13.8", "author": "Jeremy Ashkenas ", "license": "MIT", "homepage": "https://underscorejs.org", "repository": { "type": "git", "url": "git://github.com/jashkenas/underscore.git" }, "keywords": [ "util", "functional", "server", "client", "browser" ], "main": "underscore-umd.js", "module": "modules/index-all.js", "type": "commonjs", "exports": { ".": { "import": { "module": "./modules/index-all.js", "browser": { "production": "./underscore-esm-min.js", "default": "./underscore-esm.js" }, "node": "./underscore-node.mjs", "default": "./underscore-esm.js" }, "require": { "module": "./modules/index-all.js", "browser": { "production": "./underscore-umd-min.js", "default": "./underscore-umd.js" }, "node": "./underscore-node.cjs", "default": "./underscore-umd.js" }, "default": "./underscore-umd.js" }, "./underscore*": "./underscore*", "./modules/*": { "require": "./cjs/*", "default": "./modules/*" }, "./amd/*": "./amd/*", "./cjs/*": "./cjs/*", "./package.json": "./package.json" }, "devDependencies": { "coveralls": "^3.1.1", "cpy-cli": "^3.1.1", "docco": "^0.8.0", "eslint": "^6.8.0", "eslint-plugin-import": "^2.20.1", "glob": "^7.1.6", "gzip-size-cli": "^1.0.0", "husky": "^4.2.3", "karma": "^4.4.1", "karma-qunit": "^4.1.2", "karma-sauce-launcher": "^4.3.6", "nyc": "^15.1.0", "patch-package": "^6.4.7", "pretty-bytes-cli": "^1.0.0", "qunit": "2.10.1", "rollup": "^2.40.0", "terser": "^4.6.13" }, "overrides": { "colors@>1.4.0": "1.4.0" }, "scripts": { "test": "npm run lint && npm run prepare-tests && npm run test-node", "coverage": "npm run prepare-tests && nyc npm run test-node && nyc report", "coveralls": "nyc npm run test-node && nyc report --reporter=text-lcov | coveralls", "lint": "eslint modules/*.js test/*.js", "test-node": "qunit test/", "test-browser": "npm i karma-phantomjs-launcher && karma start", "bundle": "rollup -c && eslint underscore-umd.js && rollup -c rollup.config2.js", "bundle-treeshake": "cd test-treeshake && rollup --config", "prepare-tests": "npm run bundle && npm run bundle-treeshake", "minify-umd": "terser underscore-umd.js -c \"evaluate=false\" --comments \"/ .*/\" -m", "minify-esm": "terser underscore-esm.js -c \"evaluate=false\" --comments \"/ .*/\" -m", "module-package-json": "node -e 'console.log(`{\"type\":\"module\",\"version\":\"${process.env.npm_package_version}\"}`)' > modules/package.json", "build-umd": "npm run minify-umd -- --source-map content=underscore-umd.js.map --source-map-url \" \" -o underscore-umd-min.js", "build-esm": "npm run module-package-json && npm run minify-esm -- --source-map content=underscore-esm.js.map --source-map-url \" \" -o underscore-esm-min.js", "alias-bundle": "cpy --rename=underscore.js underscore-umd.js . && cpy --rename=underscore-min.js underscore-umd-min.js . && cpy --rename=underscore-min.js.map underscore-umd-min.js.map .", "build": "npm run bundle && npm run build-umd && npm run build-esm && npm run alias-bundle", "doc": "patch-package && docco underscore-esm.js && docco modules/*.js -c docco.css -t docs/linked-esm.jst", "weight": "npm run bundle && npm run minify-umd | gzip-size | pretty-bytes", "prepublishOnly": "npm run build && npm run doc" }, "files": [ "underscore-esm.js", "underscore-esm.js.map", "underscore-esm-min.js", "underscore-esm-min.js.map", "underscore-umd.js", "underscore-umd.js.map", "underscore-umd-min.js", "underscore-umd-min.js.map", "underscore.js", "underscore-min.js", "underscore-min.js.map", "underscore-node-f.cjs", "underscore-node-f.cjs.map", "underscore-node.cjs", "underscore-node.cjs.map", "underscore-node.mjs", "underscore-node.mjs.map", "modules/", "amd/", "cjs/" ], "husky": { "hooks": { "pre-commit": "npm run bundle && git add underscore-umd.js underscore-umd.js.map underscore-esm.js underscore-esm.js.map underscore-node-f.cjs underscore-node-f.cjs.map underscore-node.cjs underscore-node.cjs.map underscore-node.mjs underscore-node.mjs.map", "post-commit": "git reset underscore-umd.js underscore-umd.js.map underscore-esm.js underscore-esm.js.map underscore-node-f.cjs underscore-node-f.cjs.map underscore-node.cjs underscore-node.cjs.map underscore-node.mjs underscore-node.mjs.map" } } } ================================================ FILE: patches/docco+0.8.0.patch ================================================ diff --git a/node_modules/docco/docco.js b/node_modules/docco/docco.js index 0bb5a8b..f38f9a5 100644 --- a/node_modules/docco/docco.js +++ b/node_modules/docco/docco.js @@ -314,7 +314,7 @@ path = require('path'); - marked = require('marked'); + marked = require('marked').marked; commander = require('commander'); ================================================ FILE: rollup.common.js ================================================ import { readFileSync } from 'fs'; import { extend } from './underscore-esm.js'; var intro = readFileSync('modules/index.js', 'utf-8').split('\n').slice(3, 7).join('\n'); var outputBase = { strict: false, externalLiveBindings: false, freeze: false, }; var sourcemapBase = { sourcemap: true, sourcemapExcludeSources: true, }; export function outputConf(particular) { return extend(particular, outputBase); } export function sourcemapConf(particular) { return extend(particular, outputBase, sourcemapBase); } export function monolithConf(particular) { return extend(particular, outputBase, sourcemapBase, {intro}); } ================================================ FILE: rollup.config.js ================================================ import glob from 'glob'; import { filter } from './underscore-esm.js'; import { outputConf, sourcemapConf, monolithConf } from './rollup.common.js'; export default [ // Monolithic ESM bundle for browsers and deno. { input: 'modules/index-all.js', treeshake: false, output: monolithConf({ file: 'underscore-esm.js', format: 'esm', }), }, // Monolithic UMD bundle for browsers, AMD and old Node.js. { input: 'modules/index-default.js', treeshake: false, output: monolithConf({ file: 'underscore-umd.js', exports: 'default', format: 'umd', name: '_', amd: { id: 'underscore', }, noConflict: true, }), }, // Custom builds for Node.js, first pass. Second pass in rollup.config2.js. { input: { 'underscore-node-cjs-pre': 'modules/index-default.js', 'underscore-node-mjs-pre': 'modules/index-all.js', }, treeshake: false, output: sourcemapConf({ chunkFileNames: 'underscore-node-f-pre.js', dir: '.', minifyInternalExports: false, format: 'esm', }), }, // AMD and CJS versions of the individual modules for development // and custom bundles. { input: filter( glob.sync('modules/**/*.js'), function(path) { return path !== 'modules/index-all.js'; } ), preserveModules: true, output: [ outputConf({ dir: 'amd', exports: 'auto', format: 'amd', }), outputConf({ dir: 'cjs', exports: 'auto', format: 'cjs', }), ], } ]; ================================================ FILE: rollup.config2.js ================================================ import { resolve } from 'path'; import { monolithConf } from './rollup.common.js'; var sharedInput = './underscore-node-f-pre.js'; var sharedOutput = './underscore-node-f.cjs'; export default [ // ESM entry point for Node.js 12+. { input: 'underscore-node-mjs-pre.js', external: sharedInput, output: monolithConf({ file: 'underscore-node.mjs', format: 'esm', paths: { [resolve(__dirname, sharedInput)]: sharedOutput, }, }), }, // CJS entry point for Node.js 12+, plus code shared with the ESM entry. { input: { 'underscore-node-f': sharedInput, 'underscore-node': 'underscore-node-cjs-pre.js', }, preserveModules: true, output: monolithConf({ entryFileNames: '[name].cjs', dir: '.', exports: 'auto', format: 'cjs', }), }, ]; ================================================ FILE: test/.eslintrc ================================================ { "env": { "browser": true }, "parserOptions": {}, "globals": { "QUnit": false }, "rules": { "brace-style": 0, "no-new-wrappers": 0, "no-extend-native": 0 } } ================================================ FILE: test/arrays.js ================================================ (function() { var _ = typeof require == 'function' ? require('..') : window._; QUnit.module('Arrays'); QUnit.test('first', function(assert) { assert.strictEqual(_.first([1, 2, 3]), 1, 'can pull out the first element of an array'); assert.strictEqual(_([1, 2, 3]).first(), 1, 'can perform OO-style "first()"'); assert.deepEqual(_.first([1, 2, 3], 0), [], 'returns an empty array when n <= 0 (0 case)'); assert.deepEqual(_.first([1, 2, 3], -1), [], 'returns an empty array when n <= 0 (negative case)'); assert.deepEqual(_.first([1, 2, 3], 2), [1, 2], 'can fetch the first n elements'); assert.deepEqual(_.first([1, 2, 3], 5), [1, 2, 3], 'returns the whole array if n > length'); var result = (function(){ return _.first(arguments); }(4, 3, 2, 1)); assert.strictEqual(result, 4, 'works on an arguments object'); result = _.map([[1, 2, 3], [], [1, 2, 3]], _.first); assert.deepEqual(result, [1, void 0, 1], 'works well with _.map'); assert.strictEqual(_.first(null), void 0, 'returns undefined when called on null'); assert.deepEqual(_.first([], 10), [], 'returns an empty array when called with an explicit number of elements to return'); assert.deepEqual(_.first([], 1), [], 'returns an empty array when called with an explicit number of elements to return'); assert.deepEqual(_.first(null, 5), [], 'returns an empty array when called with an explicit number of elements to return'); Array.prototype[0] = 'boo'; assert.strictEqual(_.first([]), void 0, 'return undefined when called on a empty array'); delete Array.prototype[0]; }); QUnit.test('head', function(assert) { assert.strictEqual(_.head, _.first, 'is an alias for first'); }); QUnit.test('take', function(assert) { assert.strictEqual(_.take, _.first, 'is an alias for first'); }); QUnit.test('rest', function(assert) { var numbers = [1, 2, 3, 4]; assert.deepEqual(_.rest(numbers), [2, 3, 4], 'fetches all but the first element'); assert.deepEqual(_.rest(numbers, 0), [1, 2, 3, 4], 'returns the whole array when index is 0'); assert.deepEqual(_.rest(numbers, 2), [3, 4], 'returns elements starting at the given index'); var result = (function(){ return _(arguments).rest(); }(1, 2, 3, 4)); assert.deepEqual(result, [2, 3, 4], 'works on an arguments object'); result = _.map([[1, 2, 3], [1, 2, 3]], _.rest); assert.deepEqual(_.flatten(result), [2, 3, 2, 3], 'works well with _.map'); }); QUnit.test('tail', function(assert) { assert.strictEqual(_.tail, _.rest, 'is an alias for rest'); }); QUnit.test('drop', function(assert) { assert.strictEqual(_.drop, _.rest, 'is an alias for rest'); }); QUnit.test('initial', function(assert) { assert.deepEqual(_.initial([1, 2, 3, 4, 5]), [1, 2, 3, 4], 'returns all but the last element'); assert.deepEqual(_.initial([1, 2, 3, 4], 2), [1, 2], 'returns all but the last n elements'); assert.deepEqual(_.initial([1, 2, 3, 4], 6), [], 'returns an empty array when n > length'); var result = (function(){ return _(arguments).initial(); }(1, 2, 3, 4)); assert.deepEqual(result, [1, 2, 3], 'works on an arguments object'); result = _.map([[1, 2, 3], [1, 2, 3]], _.initial); assert.deepEqual(_.flatten(result), [1, 2, 1, 2], 'works well with _.map'); }); QUnit.test('last', function(assert) { assert.strictEqual(_.last([1, 2, 3]), 3, 'can pull out the last element of an array'); assert.strictEqual(_([1, 2, 3]).last(), 3, 'can perform OO-style "last()"'); assert.deepEqual(_.last([1, 2, 3], 0), [], 'returns an empty array when n <= 0 (0 case)'); assert.deepEqual(_.last([1, 2, 3], -1), [], 'returns an empty array when n <= 0 (negative case)'); assert.deepEqual(_.last([1, 2, 3], 2), [2, 3], 'can fetch the last n elements'); assert.deepEqual(_.last([1, 2, 3], 5), [1, 2, 3], 'returns the whole array if n > length'); var result = (function(){ return _(arguments).last(); }(1, 2, 3, 4)); assert.strictEqual(result, 4, 'works on an arguments object'); result = _.map([[1, 2, 3], [], [1, 2, 3]], _.last); assert.deepEqual(result, [3, void 0, 3], 'works well with _.map'); assert.strictEqual(_.last(null), void 0, 'returns undefined when called on null'); assert.deepEqual(_.last([], 10), [], 'returns an empty array when called with an explicit number of elements to return'); assert.deepEqual(_.last([], 1), [], 'returns an empty array when called with an explicit number of elements to return'); assert.deepEqual(_.last(null, 5), [], 'returns an empty array when called with an explicit number of elements to return'); var arr = []; arr[-1] = 'boo'; assert.strictEqual(_.last(arr), void 0, 'return undefined when called on a empty array'); }); QUnit.test('compact', function(assert) { assert.deepEqual(_.compact([1, false, null, 0, '', void 0, NaN, 2]), [1, 2], 'removes all falsy values'); var result = (function(){ return _.compact(arguments); }(0, 1, false, 2, false, 3)); assert.deepEqual(result, [1, 2, 3], 'works on an arguments object'); result = _.map([[1, false, false], [false, false, 3]], _.compact); assert.deepEqual(result, [[1], [3]], 'works well with _.map'); }); QUnit.test('flatten', function(assert) { assert.deepEqual(_.flatten(null), [], 'supports null'); assert.deepEqual(_.flatten(void 0), [], 'supports undefined'); assert.deepEqual(_.flatten([[], [[]], []]), [], 'supports empty arrays'); assert.deepEqual(_.flatten([[], [[]], []], true), [[]], 'can shallowly flatten empty arrays'); var list = [1, [2], [3, [[[4]]]]]; assert.deepEqual(_.flatten(list), [1, 2, 3, 4], 'can flatten nested arrays'); assert.deepEqual(_.flatten(list, true), [1, 2, 3, [[[4]]]], 'can shallowly flatten nested arrays'); assert.deepEqual(_.flatten(list, false), [1, 2, 3, 4], 'false means deep'); var result = (function(){ return _.flatten(arguments); }(1, [2], [3, [[[4]]]])); assert.deepEqual(result, [1, 2, 3, 4], 'works on an arguments object'); list = [[1], [2], [3], [[4]]]; assert.deepEqual(_.flatten(list, true), [1, 2, 3, [4]], 'can shallowly flatten arrays containing only other arrays'); list = [1, [2], [[3]], [[[4]]]]; assert.deepEqual(_.flatten(list, 2), [1, 2, 3, [4]], 'can flatten arrays to a given depth'); assert.deepEqual(_.flatten(list, 0), list, 'can flatten arrays to depth of 0'); assert.deepEqual(_.flatten(list, -1), list, 'can flatten arrays to depth of -1'); assert.strictEqual(_.flatten([_.range(10), _.range(10), 5, 1, 3], true).length, 23, 'can flatten medium length arrays'); assert.strictEqual(_.flatten([_.range(10), _.range(10), 5, 1, 3]).length, 23, 'can shallowly flatten medium length arrays'); assert.strictEqual(_.flatten([new Array(10)]).length, 10, 'can flatten array with nulls of size n'); assert.strictEqual(_.flatten([new Array(1000000), _.range(56000), 5, 1, 3]).length, 1056003, 'can handle massive arrays'); assert.strictEqual(_.flatten([new Array(1000000), _.range(56000), 5, 1, 3], true).length, 1056003, 'can handle massive arrays in shallow mode'); // Check against extremely deep recursion because of CVE-2026-27601. var x = _.range(100000); for (var i = 0; i < 1000; i++) x = [x]; assert.deepEqual(_.flatten(x), _.range(100000), 'can handle very deep arrays'); assert.deepEqual(_.flatten(x, true), x[0], 'can handle very deep arrays in shallow mode'); var y = [1, 2, 3]; for (var i = 0; i < 100000; ++i) y = [y]; assert.deepEqual(_.flatten(y), [1, 2, 3], 'can handle extremely deeply nested arrays'); }); QUnit.test('without', function(assert) { var list = [1, 2, 1, 0, 3, 1, 4]; assert.deepEqual(_.without(list, 0, 1), [2, 3, 4], 'removes all instances of the given values'); var result = (function(){ return _.without(arguments, 0, 1); }(1, 2, 1, 0, 3, 1, 4)); assert.deepEqual(result, [2, 3, 4], 'works on an arguments object'); list = [{one: 1}, {two: 2}]; assert.deepEqual(_.without(list, {one: 1}), list, 'compares objects by reference (value case)'); assert.deepEqual(_.without(list, list[0]), [{two: 2}], 'compares objects by reference (reference case)'); }); QUnit.test('sortedIndex', function(assert) { var numbers = [10, 20, 30, 30, 30, 40, 50, 60]; var indexFor35 = _.sortedIndex(numbers, 35); assert.strictEqual(indexFor35, 5, 'finds the index at which a value should be inserted to retain order'); var indexFor30 = _.sortedIndex(numbers, 30); assert.strictEqual(indexFor30, 2, 'finds the smallest index at which a value could be inserted to retain order'); var objects = [{x: 10}, {x: 20}, {x: 30}, {x: 40}]; var iterator = function(obj){ return obj.x; }; assert.strictEqual(_.sortedIndex(objects, {x: 25}, iterator), 2, 'uses the result of `iterator` for order comparisons'); assert.strictEqual(_.sortedIndex(objects, {x: 35}, 'x'), 3, 'when `iterator` is a string, uses that key for order comparisons'); var context = {1: 2, 2: 3, 3: 4}; iterator = function(obj){ return this[obj]; }; assert.strictEqual(_.sortedIndex([1, 3], 2, iterator, context), 1, 'can execute its iterator in the given context'); var values = [0, 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535, 131071, 262143, 524287, 1048575, 2097151, 4194303, 8388607, 16777215, 33554431, 67108863, 134217727, 268435455, 536870911, 1073741823, 2147483647]; var largeArray = Array(Math.pow(2, 32) - 1); var length = values.length; // Sparsely populate `array` while (length--) { largeArray[values[length]] = values[length]; } assert.strictEqual(_.sortedIndex(largeArray, 2147483648), 2147483648, 'works with large indexes'); }); QUnit.test('uniq', function(assert) { var list = [1, 2, 1, 3, 1, 4]; assert.deepEqual(_.uniq(list), [1, 2, 3, 4], 'can find the unique values of an unsorted array'); list = [1, 1, 1, 2, 2, 3]; assert.deepEqual(_.uniq(list, true), [1, 2, 3], 'can find the unique values of a sorted array faster'); list = [-2, -1, 0, 1, 2]; var notInjective = function(x) {return x * x;}; assert.deepEqual(_.uniq(list, true, notInjective), [-2, -1, 0], 'can find values of sorted array which map to unique values through a non one-to-one function by switching to slower algorithm even when isSorted=true'); list = [{name: 'Moe'}, {name: 'Curly'}, {name: 'Larry'}, {name: 'Curly'}]; var expected = [{name: 'Moe'}, {name: 'Curly'}, {name: 'Larry'}]; var iterator = function(stooge) { return stooge.name; }; assert.deepEqual(_.uniq(list, false, iterator), expected, 'uses the result of `iterator` for uniqueness comparisons (unsorted case)'); assert.deepEqual(_.uniq(list, iterator), expected, '`sorted` argument defaults to false when omitted'); assert.deepEqual(_.uniq(list, 'name'), expected, 'when `iterator` is a string, uses that key for comparisons (unsorted case)'); list = [{score: 8}, {score: 10}, {score: 10}]; expected = [{score: 8}, {score: 10}]; iterator = function(item) { return item.score; }; assert.deepEqual(_.uniq(list, true, iterator), expected, 'uses the result of `iterator` for uniqueness comparisons (sorted case)'); assert.deepEqual(_.uniq(list, true, 'score'), expected, 'when `iterator` is a string, uses that key for comparisons (sorted case)'); assert.deepEqual(_.uniq([{0: 1}, {0: 1}, {0: 1}, {0: 2}], 0), [{0: 1}, {0: 2}], 'can use falsy pluck like iterator'); var result = (function(){ return _.uniq(arguments); }(1, 2, 1, 3, 1, 4)); assert.deepEqual(result, [1, 2, 3, 4], 'works on an arguments object'); var a = {}, b = {}, c = {}; assert.deepEqual(_.uniq([a, b, a, b, c]), [a, b, c], 'works on values that can be tested for equivalency but not ordered'); assert.deepEqual(_.uniq(null), [], 'returns an empty array when `array` is not iterable'); var context = {}; list = [3]; _.uniq(list, function(value, index, array) { assert.strictEqual(this, context, 'executes its iterator in the given context'); assert.strictEqual(value, 3, 'passes its iterator the value'); assert.strictEqual(index, 0, 'passes its iterator the index'); assert.strictEqual(array, list, 'passes its iterator the entire array'); }, context); }); QUnit.test('unique', function(assert) { assert.strictEqual(_.unique, _.uniq, 'is an alias for uniq'); }); QUnit.test('intersection', function(assert) { var stooges = ['moe', 'curly', 'larry'], leaders = ['moe', 'groucho']; assert.deepEqual(_.intersection(stooges, leaders), ['moe'], 'can find the set intersection of two arrays'); assert.deepEqual(_(stooges).intersection(leaders), ['moe'], 'can perform an OO-style intersection'); var result = (function(){ return _.intersection(arguments, leaders); }('moe', 'curly', 'larry')); assert.deepEqual(result, ['moe'], 'works on an arguments object'); var theSixStooges = ['moe', 'moe', 'curly', 'curly', 'larry', 'larry']; assert.deepEqual(_.intersection(theSixStooges, leaders), ['moe'], 'returns a duplicate-free array'); result = _.intersection([2, 4, 3, 1], [1, 2, 3]); assert.deepEqual(result, [2, 3, 1], 'preserves the order of the first array'); result = _.intersection(null, [1, 2, 3]); assert.deepEqual(result, [], 'returns an empty array when passed null as the first argument'); result = _.intersection([1, 2, 3], null); assert.deepEqual(result, [], 'returns an empty array when passed null as an argument beyond the first'); }); QUnit.test('union', function(assert) { var result = _.union([1, 2, 3], [2, 30, 1], [1, 40]); assert.deepEqual(result, [1, 2, 3, 30, 40], 'can find the union of a list of arrays'); result = _([1, 2, 3]).union([2, 30, 1], [1, 40]); assert.deepEqual(result, [1, 2, 3, 30, 40], 'can perform an OO-style union'); result = _.union([1, 2, 3], [2, 30, 1], [1, 40, [1]]); assert.deepEqual(result, [1, 2, 3, 30, 40, [1]], 'can find the union of a list of nested arrays'); result = _.union([10, 20], [1, 30, 10], [0, 40]); assert.deepEqual(result, [10, 20, 1, 30, 0, 40], 'orders values by their first encounter'); result = (function(){ return _.union(arguments, [2, 30, 1], [1, 40]); }(1, 2, 3)); assert.deepEqual(result, [1, 2, 3, 30, 40], 'works on an arguments object'); assert.deepEqual(_.union([1, 2, 3], 4), [1, 2, 3], 'restricts the union to arrays only'); }); QUnit.test('difference', function(assert) { var result = _.difference([1, 2, 3], [2, 30, 40]); assert.deepEqual(result, [1, 3], 'can find the difference of two arrays'); var result = _.difference([1, 2, 3], [2, 30, 40, [1]]); assert.deepEqual(result, [1, 3], 'avoids deep flattening of arrays'); result = _([1, 2, 3]).difference([2, 30, 40]); assert.deepEqual(result, [1, 3], 'can perform an OO-style difference'); result = _.difference([1, 2, 3, 4], [2, 30, 40], [1, 11, 111]); assert.deepEqual(result, [3, 4], 'can find the difference of three arrays'); result = _.difference([8, 9, 3, 1], [3, 8]); assert.deepEqual(result, [9, 1], 'preserves the order of the first array'); result = (function(){ return _.difference(arguments, [2, 30, 40]); }(1, 2, 3)); assert.deepEqual(result, [1, 3], 'works on an arguments object'); result = _.difference([1, 2, 3], 1); assert.deepEqual(result, [1, 2, 3], 'restrict the difference to arrays only'); }); QUnit.test('zip', function(assert) { var names = ['moe', 'larry', 'curly'], ages = [30, 40, 50], leaders = [true]; assert.deepEqual(_.zip(names, ages, leaders), [ ['moe', 30, true], ['larry', 40, void 0], ['curly', 50, void 0] ], 'zipped together arrays of different lengths'); var stooges = _.zip(['moe', 30, 'stooge 1'], ['larry', 40, 'stooge 2'], ['curly', 50, 'stooge 3']); assert.deepEqual(stooges, [['moe', 'larry', 'curly'], [30, 40, 50], ['stooge 1', 'stooge 2', 'stooge 3']], 'zipped pairs'); // In the case of different lengths of the tuples, undefined values // should be used as placeholder stooges = _.zip(['moe', 30], ['larry', 40], ['curly', 50, 'extra data']); assert.deepEqual(stooges, [['moe', 'larry', 'curly'], [30, 40, 50], [void 0, void 0, 'extra data']], 'zipped pairs with empties'); var empty = _.zip([]); assert.deepEqual(empty, [], 'unzipped empty'); assert.deepEqual(_.zip(null), [], 'handles null'); assert.deepEqual(_.zip(), [], '_.zip() returns []'); }); QUnit.test('unzip', function(assert) { assert.deepEqual(_.unzip(null), [], 'handles null'); assert.deepEqual(_.unzip([['a', 'b'], [1, 2]]), [['a', 1], ['b', 2]]); // complements zip var zipped = _.zip(['fred', 'barney'], [30, 40], [true, false]); assert.deepEqual(_.unzip(zipped), [['fred', 'barney'], [30, 40], [true, false]]); zipped = _.zip(['moe', 30], ['larry', 40], ['curly', 50, 'extra data']); assert.deepEqual(_.unzip(zipped), [['moe', 30, void 0], ['larry', 40, void 0], ['curly', 50, 'extra data']], 'Uses length of largest array'); }); QUnit.test('object', function(assert) { var result = _.object(['moe', 'larry', 'curly'], [30, 40, 50]); var shouldBe = {moe: 30, larry: 40, curly: 50}; assert.deepEqual(result, shouldBe, 'two arrays zipped together into an object'); result = _.object([['one', 1], ['two', 2], ['three', 3]]); shouldBe = {one: 1, two: 2, three: 3}; assert.deepEqual(result, shouldBe, 'an array of pairs zipped together into an object'); var stooges = {moe: 30, larry: 40, curly: 50}; assert.deepEqual(_.object(_.pairs(stooges)), stooges, 'an object converted to pairs and back to an object'); assert.deepEqual(_.object(null), {}, 'handles nulls'); }); QUnit.test('transpose', function(assert) { assert.strictEqual(_.transpose, _.unzip, 'is an alias for unzip'); }); QUnit.test('indexOf', function(assert) { var numbers = [1, 2, 3]; assert.strictEqual(_.indexOf(numbers, 2), 1, 'can compute indexOf'); var result = (function(){ return _.indexOf(arguments, 2); }(1, 2, 3)); assert.strictEqual(result, 1, 'works on an arguments object'); _.each([null, void 0, [], false], function(val) { var msg = 'Handles: ' + (_.isArray(val) ? '[]' : val); assert.strictEqual(_.indexOf(val, 2), -1, msg); assert.strictEqual(_.indexOf(val, 2, -1), -1, msg); assert.strictEqual(_.indexOf(val, 2, -20), -1, msg); assert.strictEqual(_.indexOf(val, 2, 15), -1, msg); }); var num = 35; numbers = [10, 20, 30, 40, 50]; var index = _.indexOf(numbers, num, true); assert.strictEqual(index, -1, '35 is not in the list'); numbers = [10, 20, 30, 40, 50]; num = 40; index = _.indexOf(numbers, num, true); assert.strictEqual(index, 3, '40 is in the list'); numbers = [1, 40, 40, 40, 40, 40, 40, 40, 50, 60, 70]; num = 40; assert.strictEqual(_.indexOf(numbers, num, true), 1, '40 is in the list'); assert.strictEqual(_.indexOf(numbers, 6, true), -1, '6 isnt in the list'); assert.strictEqual(_.indexOf([1, 2, 5, 4, 6, 7], 5, true), -1, 'sorted indexOf doesn\'t use binary search'); assert.ok(_.every(['1', [], {}, null], function() { return _.indexOf(numbers, num, {}) === 1; }), 'non-nums as fromIndex make indexOf assume sorted'); numbers = [1, 2, 3, 1, 2, 3, 1, 2, 3]; index = _.indexOf(numbers, 2, 5); assert.strictEqual(index, 7, 'supports the fromIndex argument'); index = _.indexOf([,,, 0], void 0); assert.strictEqual(index, 0, 'treats sparse arrays as if they were dense'); var array = [1, 2, 3, 1, 2, 3]; assert.strictEqual(_.indexOf(array, 1, -3), 3, 'neg `fromIndex` starts at the right index'); assert.strictEqual(_.indexOf(array, 1, -2), -1, 'neg `fromIndex` starts at the right index'); assert.strictEqual(_.indexOf(array, 2, -3), 4); _.each([-6, -8, -Infinity], function(fromIndex) { assert.strictEqual(_.indexOf(array, 1, fromIndex), 0); }); assert.strictEqual(_.indexOf([1, 2, 3], 1, true), 0); index = _.indexOf([], void 0, true); assert.strictEqual(index, -1, 'empty array with truthy `isSorted` returns -1'); }); QUnit.test('indexOf with NaN', function(assert) { assert.strictEqual(_.indexOf([1, 2, NaN, NaN], NaN), 2, 'Expected [1, 2, NaN] to contain NaN'); assert.strictEqual(_.indexOf([1, 2, Infinity], NaN), -1, 'Expected [1, 2, Infinity] to NOT contain NaN'); assert.strictEqual(_.indexOf([1, 2, NaN, NaN], NaN, 1), 2, 'startIndex does not affect result'); assert.strictEqual(_.indexOf([1, 2, NaN, NaN], NaN, -2), 2, 'startIndex does not affect result'); (function() { assert.strictEqual(_.indexOf(arguments, NaN), 2, 'Expected arguments [1, 2, NaN] to contain NaN'); }(1, 2, NaN, NaN)); }); QUnit.test('indexOf with +- 0', function(assert) { _.each([-0, +0], function(val) { assert.strictEqual(_.indexOf([1, 2, val, val], val), 2); assert.strictEqual(_.indexOf([1, 2, val, val], -val), 2); }); }); QUnit.test('lastIndexOf', function(assert) { var numbers = [1, 0, 1]; var falsy = [void 0, '', 0, false, NaN, null, void 0]; assert.strictEqual(_.lastIndexOf(numbers, 1), 2); numbers = [1, 0, 1, 0, 0, 1, 0, 0, 0]; numbers.lastIndexOf = null; assert.strictEqual(_.lastIndexOf(numbers, 1), 5, 'can compute lastIndexOf, even without the native function'); assert.strictEqual(_.lastIndexOf(numbers, 0), 8, 'lastIndexOf the other element'); var result = (function(){ return _.lastIndexOf(arguments, 1); }(1, 0, 1, 0, 0, 1, 0, 0, 0)); assert.strictEqual(result, 5, 'works on an arguments object'); _.each([null, void 0, [], false], function(val) { var msg = 'Handles: ' + (_.isArray(val) ? '[]' : val); assert.strictEqual(_.lastIndexOf(val, 2), -1, msg); assert.strictEqual(_.lastIndexOf(val, 2, -1), -1, msg); assert.strictEqual(_.lastIndexOf(val, 2, -20), -1, msg); assert.strictEqual(_.lastIndexOf(val, 2, 15), -1, msg); }); numbers = [1, 2, 3, 1, 2, 3, 1, 2, 3]; var index = _.lastIndexOf(numbers, 2, 2); assert.strictEqual(index, 1, 'supports the fromIndex argument'); var array = [1, 2, 3, 1, 2, 3]; assert.strictEqual(_.lastIndexOf(array, 1, 0), 0, 'starts at the correct from idx'); assert.strictEqual(_.lastIndexOf(array, 3), 5, 'should return the index of the last matched value'); assert.strictEqual(_.lastIndexOf(array, 4), -1, 'should return `-1` for an unmatched value'); assert.strictEqual(_.lastIndexOf(array, 1, 2), 0, 'should work with a positive `fromIndex`'); _.each([6, 8, Math.pow(2, 32), Infinity], function(fromIndex) { assert.strictEqual(_.lastIndexOf(array, void 0, fromIndex), -1); assert.strictEqual(_.lastIndexOf(array, 1, fromIndex), 3); assert.strictEqual(_.lastIndexOf(array, '', fromIndex), -1); }); var expected = _.map(falsy, function(value) { return typeof value == 'number' ? -1 : 5; }); var actual = _.map(falsy, function(fromIndex) { return _.lastIndexOf(array, 3, fromIndex); }); assert.deepEqual(actual, expected, 'should treat falsy `fromIndex` values, except `0` and `NaN`, as `array.length`'); assert.strictEqual(_.lastIndexOf(array, 3, '1'), 5, 'should treat non-number `fromIndex` values as `array.length`'); assert.strictEqual(_.lastIndexOf(array, 3, true), 5, 'should treat non-number `fromIndex` values as `array.length`'); assert.strictEqual(_.lastIndexOf(array, 2, -3), 1, 'should work with a negative `fromIndex`'); assert.strictEqual(_.lastIndexOf(array, 1, -3), 3, 'neg `fromIndex` starts at the right index'); assert.deepEqual(_.map([-6, -8, -Infinity], function(fromIndex) { return _.lastIndexOf(array, 1, fromIndex); }), [0, -1, -1]); }); QUnit.test('lastIndexOf with NaN', function(assert) { assert.strictEqual(_.lastIndexOf([1, 2, NaN, NaN], NaN), 3, 'Expected [1, 2, NaN] to contain NaN'); assert.strictEqual(_.lastIndexOf([1, 2, Infinity], NaN), -1, 'Expected [1, 2, NaN] to contain NaN'); assert.strictEqual(_.lastIndexOf([1, 2, NaN, NaN], NaN, 2), 2, 'fromIndex does not affect result'); assert.strictEqual(_.lastIndexOf([1, 2, NaN, NaN], NaN, -2), 2, 'fromIndex does not affect result'); (function() { assert.strictEqual(_.lastIndexOf(arguments, NaN), 3, 'Expected arguments [1, 2, NaN] to contain NaN'); }(1, 2, NaN, NaN)); }); QUnit.test('lastIndexOf with +- 0', function(assert) { _.each([-0, +0], function(val) { assert.strictEqual(_.lastIndexOf([1, 2, val, val], val), 3); assert.strictEqual(_.lastIndexOf([1, 2, val, val], -val), 3); assert.strictEqual(_.lastIndexOf([-1, 1, 2], -val), -1); }); }); QUnit.test('findIndex', function(assert) { var objects = [ {a: 0, b: 0}, {a: 1, b: 1}, {a: 2, b: 2}, {a: 0, b: 0} ]; assert.strictEqual(_.findIndex(objects, function(obj) { return obj.a === 0; }), 0); assert.strictEqual(_.findIndex(objects, function(obj) { return obj.b * obj.a === 4; }), 2); assert.strictEqual(_.findIndex(objects, 'a'), 1, 'Uses lookupIterator'); assert.strictEqual(_.findIndex(objects, function(obj) { return obj.b * obj.a === 5; }), -1); assert.strictEqual(_.findIndex(null, _.noop), -1); assert.strictEqual(_.findIndex(objects, function(a) { return a.foo === null; }), -1); _.findIndex([{a: 1}], function(a, key, obj) { assert.strictEqual(key, 0); assert.deepEqual(obj, [{a: 1}]); assert.strictEqual(this, objects, 'called with context'); }, objects); var sparse = []; sparse[20] = {a: 2, b: 2}; assert.strictEqual(_.findIndex(sparse, function(obj) { return obj && obj.b * obj.a === 4; }), 20, 'Works with sparse arrays'); var array = [1, 2, 3, 4]; array.match = 55; assert.strictEqual(_.findIndex(array, function(x) { return x === 55; }), -1, 'doesn\'t match array-likes keys'); }); QUnit.test('findLastIndex', function(assert) { var objects = [ {a: 0, b: 0}, {a: 1, b: 1}, {a: 2, b: 2}, {a: 0, b: 0} ]; assert.strictEqual(_.findLastIndex(objects, function(obj) { return obj.a === 0; }), 3); assert.strictEqual(_.findLastIndex(objects, function(obj) { return obj.b * obj.a === 4; }), 2); assert.strictEqual(_.findLastIndex(objects, 'a'), 2, 'Uses lookupIterator'); assert.strictEqual(_.findLastIndex(objects, function(obj) { return obj.b * obj.a === 5; }), -1); assert.strictEqual(_.findLastIndex(null, _.noop), -1); assert.strictEqual(_.findLastIndex(objects, function(a) { return a.foo === null; }), -1); _.findLastIndex([{a: 1}], function(a, key, obj) { assert.strictEqual(key, 0); assert.deepEqual(obj, [{a: 1}]); assert.strictEqual(this, objects, 'called with context'); }, objects); var sparse = []; sparse[20] = {a: 2, b: 2}; assert.strictEqual(_.findLastIndex(sparse, function(obj) { return obj && obj.b * obj.a === 4; }), 20, 'Works with sparse arrays'); var array = [1, 2, 3, 4]; array.match = 55; assert.strictEqual(_.findLastIndex(array, function(x) { return x === 55; }), -1, 'doesn\'t match array-likes keys'); }); QUnit.test('range', function(assert) { assert.deepEqual(_.range(0), [], 'range with 0 as a first argument generates an empty array'); assert.deepEqual(_.range(4), [0, 1, 2, 3], 'range with a single positive argument generates an array of elements 0,1,2,...,n-1'); assert.deepEqual(_.range(5, 8), [5, 6, 7], 'range with two arguments a & b, a<b generates an array of elements a,a+1,a+2,...,b-2,b-1'); assert.deepEqual(_.range(3, 10, 3), [3, 6, 9], 'range with three arguments a & b & c, c < b-a, a < b generates an array of elements a,a+c,a+2c,...,b - (multiplier of a) < c'); assert.deepEqual(_.range(3, 10, 15), [3], 'range with three arguments a & b & c, c > b-a, a < b generates an array with a single element, equal to a'); assert.deepEqual(_.range(12, 7, -2), [12, 10, 8], 'range with three arguments a & b & c, a > b, c < 0 generates an array of elements a,a-c,a-2c and ends with the number not less than b'); assert.deepEqual(_.range(0, -10, -1), [0, -1, -2, -3, -4, -5, -6, -7, -8, -9], 'final example in the Python docs'); assert.strictEqual(1 / _.range(-0, 1)[0], -Infinity, 'should preserve -0'); assert.deepEqual(_.range(8, 5), [8, 7, 6], 'negative range generates descending array'); assert.deepEqual(_.range(-3), [0, -1, -2], 'negative range generates descending array'); }); QUnit.test('chunk', function(assert) { assert.deepEqual(_.chunk([], 2), [], 'chunk for empty array returns an empty array'); assert.deepEqual(_.chunk([1, 2, 3], 0), [], 'chunk into parts of 0 elements returns empty array'); assert.deepEqual(_.chunk([1, 2, 3], -1), [], 'chunk into parts of negative amount of elements returns an empty array'); assert.deepEqual(_.chunk([1, 2, 3]), [], 'defaults to empty array (chunk size 0)'); assert.deepEqual(_.chunk([1, 2, 3], 1), [[1], [2], [3]], 'chunk into parts of 1 elements returns original array'); assert.deepEqual(_.chunk([1, 2, 3], 3), [[1, 2, 3]], 'chunk into parts of current array length elements returns the original array'); assert.deepEqual(_.chunk([1, 2, 3], 5), [[1, 2, 3]], 'chunk into parts of more then current array length elements returns the original array'); assert.deepEqual(_.chunk([10, 20, 30, 40, 50, 60, 70], 2), [[10, 20], [30, 40], [50, 60], [70]], 'chunk into parts of less then current array length elements'); assert.deepEqual(_.chunk([10, 20, 30, 40, 50, 60, 70], 3), [[10, 20, 30], [40, 50, 60], [70]], 'chunk into parts of less then current array length elements'); }); }()); ================================================ FILE: test/chaining.js ================================================ (function() { var _ = typeof require == 'function' ? require('..') : window._; QUnit.module('Chaining'); QUnit.test('map/flatten/reduce', function(assert) { var lyrics = [ 'I\'m a lumberjack and I\'m okay', 'I sleep all night and I work all day', 'He\'s a lumberjack and he\'s okay', 'He sleeps all night and he works all day' ]; var counts = _(lyrics).chain() .map(function(line) { return line.split(''); }) .flatten() .reduce(function(hash, l) { hash[l] = hash[l] || 0; hash[l]++; return hash; }, {}) .value(); assert.strictEqual(counts.a, 16, 'counted all the letters in the song'); assert.strictEqual(counts.e, 10, 'counted all the letters in the song'); }); QUnit.test('select/reject/sortBy', function(assert) { var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; numbers = _(numbers).chain().select(function(n) { return n % 2 === 0; }).reject(function(n) { return n % 4 === 0; }).sortBy(function(n) { return -n; }).value(); assert.deepEqual(numbers, [10, 6, 2], 'filtered and reversed the numbers'); }); QUnit.test('select/reject/sortBy in functional style', function(assert) { var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; numbers = _.chain(numbers).select(function(n) { return n % 2 === 0; }).reject(function(n) { return n % 4 === 0; }).sortBy(function(n) { return -n; }).value(); assert.deepEqual(numbers, [10, 6, 2], 'filtered and reversed the numbers'); }); QUnit.test('reverse/concat/unshift/pop/map', function(assert) { var numbers = [1, 2, 3, 4, 5]; numbers = _(numbers).chain() .reverse() .concat([5, 5, 5]) .unshift(17) .pop() .map(function(n){ return n * 2; }) .value(); assert.deepEqual(numbers, [34, 10, 8, 6, 4, 2, 10, 10], 'can chain together array functions.'); }); QUnit.test('splice', function(assert) { var instance = _([1, 2, 3, 4, 5]).chain(); assert.deepEqual(instance.splice(1, 3).value(), [1, 5]); assert.deepEqual(instance.splice(1, 0).value(), [1, 5]); assert.deepEqual(instance.splice(1, 1).value(), [1]); assert.deepEqual(instance.splice(0, 1).value(), [], '#397 Can create empty array'); }); QUnit.test('shift', function(assert) { var instance = _([1, 2, 3]).chain(); assert.deepEqual(instance.shift().value(), [2, 3]); assert.deepEqual(instance.shift().value(), [3]); assert.deepEqual(instance.shift().value(), [], '#397 Can create empty array'); }); QUnit.test('pop', function(assert) { var instance = _([1, 2, 3]).chain(); assert.deepEqual(instance.pop().value(), [1, 2]); assert.deepEqual(instance.pop().value(), [1]); assert.deepEqual(instance.pop().value(), [], '#397 Can create empty array'); }); QUnit.test('chaining works in small stages', function(assert) { var o = _([1, 2, 3, 4]).chain(); assert.deepEqual(o.filter(function(i) { return i < 3; }).value(), [1, 2]); assert.deepEqual(o.filter(function(i) { return i > 2; }).value(), [3, 4]); }); QUnit.test('#1562: Engine proxies for chained functions', function(assert) { var wrapped = _(512); assert.strictEqual(wrapped.toJSON(), 512); assert.strictEqual(wrapped.valueOf(), 512); assert.strictEqual(+wrapped, 512); assert.strictEqual(wrapped.toString(), '512'); assert.strictEqual('' + wrapped, '512'); }); QUnit.test('wrapper methods handle undefined and null', function(assert) { var w1 = _(), w2 = _(null); _.each([w1, w2], function(wrapped) { assert.equal(wrapped.extend({a: 1}), void 0); assert.equal(wrapped.first(), void 0); assert.equal(wrapped.push(1), void 0); assert.equal(wrapped.concat([1]), void 0); }); }); }()); ================================================ FILE: test/collections.js ================================================ (function() { var _ = typeof require == 'function' ? require('..') : window._; QUnit.module('Collections'); QUnit.test('each', function(assert) { _.each([1, 2, 3], function(num, i) { assert.strictEqual(num, i + 1, 'each iterators provide value and iteration count'); }); var answers = []; _.each([1, 2, 3], function(num){ answers.push(num * this.multiplier); }, {multiplier: 5}); assert.deepEqual(answers, [5, 10, 15], 'context object property accessed'); answers = []; _.each([1, 2, 3], function(num){ answers.push(num); }); assert.deepEqual(answers, [1, 2, 3], 'can iterate a simple array'); answers = []; var obj = {one: 1, two: 2, three: 3}; obj.constructor.prototype.four = 4; _.each(obj, function(value, key){ answers.push(key); }); assert.deepEqual(answers, ['one', 'two', 'three'], 'iterating over objects works, and ignores the object prototype.'); delete obj.constructor.prototype.four; // ensure the each function is JITed _(1000).times(function() { _.each([], function(){}); }); var count = 0; obj = {1: 'foo', 2: 'bar', 3: 'baz'}; _.each(obj, function(){ count++; }); assert.strictEqual(count, 3, 'the fun should be called only 3 times'); var answer = null; _.each([1, 2, 3], function(num, index, arr){ if (_.include(arr, num)) answer = true; }); assert.ok(answer, 'can reference the original collection from inside the iterator'); answers = 0; _.each(null, function(){ ++answers; }); assert.strictEqual(answers, 0, 'handles a null properly'); _.each(false, function(){}); var a = [1, 2, 3]; assert.strictEqual(_.each(a, function(){}), a); assert.strictEqual(_.each(null, function(){}), null); }); QUnit.test('forEach', function(assert) { assert.strictEqual(_.forEach, _.each, 'is an alias for each'); }); QUnit.test('lookupIterator with contexts', function(assert) { _.each([true, false, 'yes', '', 0, 1, {}], function(context) { _.each([1], function() { assert.strictEqual(typeof this, 'object', 'context is a wrapped primitive'); assert.strictEqual(this.valueOf(), context, 'the unwrapped context is the specified primitive'); assert.equal(this, context, 'context can be coerced to the specified primitive'); }, context); }); }); QUnit.test('Iterating objects with sketchy length properties', function(assert) { var functions = [ 'each', 'map', 'filter', 'find', 'some', 'every', 'max', 'min', 'groupBy', 'countBy', 'partition', 'indexBy' ]; var reducers = ['reduce', 'reduceRight']; var tricks = [ {length: '5'}, {length: {valueOf: _.constant(5)}}, {length: Math.pow(2, 53) + 1}, {length: Math.pow(2, 53)}, {length: null}, {length: -2}, {length: new Number(15)} ]; assert.expect(tricks.length * (functions.length + reducers.length + 4)); _.each(tricks, function(trick) { var length = trick.length; assert.strictEqual(_.size(trick), 1, 'size on obj with length: ' + length); assert.deepEqual(_.toArray(trick), [length], 'toArray on obj with length: ' + length); assert.deepEqual(_.shuffle(trick), [length], 'shuffle on obj with length: ' + length); assert.deepEqual(_.sample(trick), length, 'sample on obj with length: ' + length); _.each(functions, function(method) { _[method](trick, function(val, key) { assert.strictEqual(key, 'length', method + ': ran with length = ' + val); }); }); _.each(reducers, function(method) { assert.strictEqual(_[method](trick), trick.length, method); }); }); }); QUnit.test('Resistant to collection length and properties changing while iterating', function(assert) { var collection = [ 'each', 'map', 'filter', 'find', 'some', 'every', 'max', 'min', 'reject', 'groupBy', 'countBy', 'partition', 'indexBy', 'reduce', 'reduceRight' ]; var array = [ 'findIndex', 'findLastIndex' ]; var object = [ 'mapObject', 'findKey', 'pick', 'omit' ]; _.each(collection.concat(array), function(method) { var sparseArray = [1, 2, 3]; sparseArray.length = 100; var answers = 0; _[method](sparseArray, function(){ ++answers; return method === 'every' ? true : null; }, {}); assert.strictEqual(answers, 100, method + ' enumerates [0, length)'); var growingCollection = [1, 2, 3], count = 0; _[method](growingCollection, function() { if (count < 10) growingCollection.push(count++); return method === 'every' ? true : null; }, {}); assert.strictEqual(count, 3, method + ' is resistant to length changes'); }); _.each(collection.concat(object), function(method) { var changingObject = {0: 0, 1: 1}, count = 0; _[method](changingObject, function(val) { if (count < 10) changingObject[++count] = val + 1; return method === 'every' ? true : null; }, {}); assert.strictEqual(count, 2, method + ' is resistant to property changes'); }); }); QUnit.test('map', function(assert) { var doubled = _.map([1, 2, 3], function(num){ return num * 2; }); assert.deepEqual(doubled, [2, 4, 6], 'doubled numbers'); var tripled = _.map([1, 2, 3], function(num){ return num * this.multiplier; }, {multiplier: 3}); assert.deepEqual(tripled, [3, 6, 9], 'tripled numbers with context'); doubled = _([1, 2, 3]).map(function(num){ return num * 2; }); assert.deepEqual(doubled, [2, 4, 6], 'OO-style doubled numbers'); var ids = _.map({length: 2, 0: {id: '1'}, 1: {id: '2'}}, function(n){ return n.id; }); assert.deepEqual(ids, ['1', '2'], 'Can use collection methods on Array-likes.'); assert.deepEqual(_.map(null, _.noop), [], 'handles a null properly'); assert.deepEqual(_.map([1], function() { return this.length; }, [5]), [1], 'called with context'); // Passing a property name like _.pluck. var people = [{name: 'moe', age: 30}, {name: 'curly', age: 50}]; assert.deepEqual(_.map(people, 'name'), ['moe', 'curly'], 'predicate string map to object properties'); }); QUnit.test('collect', function(assert) { assert.strictEqual(_.collect, _.map, 'is an alias for map'); }); QUnit.test('reduce', function(assert) { var sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0); assert.strictEqual(sum, 6, 'can sum up an array'); var context = {multiplier: 3}; sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num * this.multiplier; }, 0, context); assert.strictEqual(sum, 18, 'can reduce with a context object'); sum = _([1, 2, 3]).reduce(function(memo, num){ return memo + num; }, 0); assert.strictEqual(sum, 6, 'OO-style reduce'); sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }); assert.strictEqual(sum, 6, 'default initial value'); var prod = _.reduce([1, 2, 3, 4], function(memo, num){ return memo * num; }); assert.strictEqual(prod, 24, 'can reduce via multiplication'); assert.strictEqual(_.reduce(null, _.noop, 138), 138, 'handles a null (with initial value) properly'); assert.strictEqual(_.reduce([], _.noop, void 0), void 0, 'undefined can be passed as a special case'); assert.strictEqual(_.reduce([_], _.noop), _, 'collection of length one with no initial value returns the first item'); assert.strictEqual(_.reduce([], _.noop), void 0, 'returns undefined when collection is empty and no initial value'); }); QUnit.test('foldl', function(assert) { assert.strictEqual(_.foldl, _.reduce, 'is an alias for reduce'); }); QUnit.test('inject', function(assert) { assert.strictEqual(_.inject, _.reduce, 'is an alias for reduce'); }); QUnit.test('reduceRight', function(assert) { var list = _.reduceRight(['foo', 'bar', 'baz'], function(memo, str){ return memo + str; }, ''); assert.strictEqual(list, 'bazbarfoo', 'can perform right folds'); list = _.reduceRight(['foo', 'bar', 'baz'], function(memo, str){ return memo + str; }); assert.strictEqual(list, 'bazbarfoo', 'default initial value'); var sum = _.reduceRight({a: 1, b: 2, c: 3}, function(memo, num){ return memo + num; }); assert.strictEqual(sum, 6, 'default initial value on object'); assert.strictEqual(_.reduceRight(null, _.noop, 138), 138, 'handles a null (with initial value) properly'); assert.strictEqual(_.reduceRight([_], _.noop), _, 'collection of length one with no initial value returns the first item'); assert.strictEqual(_.reduceRight([], _.noop, void 0), void 0, 'undefined can be passed as a special case'); assert.strictEqual(_.reduceRight([], _.noop), void 0, 'returns undefined when collection is empty and no initial value'); // Assert that the correct arguments are being passed. var args, init = {}, object = {a: 1, b: 2}, lastKey = _.keys(object).pop(); var expected = lastKey === 'a' ? [init, 1, 'a', object] : [init, 2, 'b', object]; _.reduceRight(object, function() { if (!args) args = _.toArray(arguments); }, init); assert.deepEqual(args, expected); // And again, with numeric keys. object = {2: 'a', 1: 'b'}; lastKey = _.keys(object).pop(); args = null; expected = lastKey === '2' ? [init, 'a', '2', object] : [init, 'b', '1', object]; _.reduceRight(object, function() { if (!args) args = _.toArray(arguments); }, init); assert.deepEqual(args, expected); }); QUnit.test('foldr', function(assert) { assert.strictEqual(_.foldr, _.reduceRight, 'is an alias for reduceRight'); }); QUnit.test('find', function(assert) { var array = [1, 2, 3, 4]; assert.strictEqual(_.find(array, function(n) { return n > 2; }), 3, 'should return first found `value`'); assert.strictEqual(_.find(array, function() { return false; }), void 0, 'should return `undefined` if `value` is not found'); array.dontmatch = 55; assert.strictEqual(_.find(array, function(x) { return x === 55; }), void 0, 'iterates array-likes correctly'); // Matching an object like _.findWhere. var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}, {a: 2, b: 4}]; assert.deepEqual(_.find(list, {a: 1}), {a: 1, b: 2}, 'can be used as findWhere'); assert.deepEqual(_.find(list, {b: 4}), {a: 1, b: 4}); assert.ok(!_.find(list, {c: 1}), 'undefined when not found'); assert.ok(!_.find([], {c: 1}), 'undefined when searching empty list'); var result = _.find([1, 2, 3], function(num){ return num * 2 === 4; }); assert.strictEqual(result, 2, 'found the first "2" and broke the loop'); var obj = { a: {x: 1, z: 3}, b: {x: 2, z: 2}, c: {x: 3, z: 4}, d: {x: 4, z: 1} }; assert.deepEqual(_.find(obj, {x: 2}), {x: 2, z: 2}, 'works on objects'); assert.deepEqual(_.find(obj, {x: 2, z: 1}), void 0); assert.deepEqual(_.find(obj, function(x) { return x.x === 4; }), {x: 4, z: 1}); _.findIndex([{a: 1}], function(a, key, o) { assert.strictEqual(key, 0); assert.deepEqual(o, [{a: 1}]); assert.strictEqual(this, _, 'called with context'); }, _); }); QUnit.test('detect', function(assert) { assert.strictEqual(_.detect, _.find, 'is an alias for find'); }); QUnit.test('filter', function(assert) { var evenArray = [1, 2, 3, 4, 5, 6]; var evenObject = {one: 1, two: 2, three: 3}; var isEven = function(num){ return num % 2 === 0; }; assert.deepEqual(_.filter(evenArray, isEven), [2, 4, 6]); assert.deepEqual(_.filter(evenObject, isEven), [2], 'can filter objects'); assert.deepEqual(_.filter([{}, evenObject, []], 'two'), [evenObject], 'predicate string map to object properties'); _.filter([1], function() { assert.strictEqual(this, evenObject, 'given context'); }, evenObject); // Can be used like _.where. var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}]; assert.deepEqual(_.filter(list, {a: 1}), [{a: 1, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}]); assert.deepEqual(_.filter(list, {b: 2}), [{a: 1, b: 2}, {a: 2, b: 2}]); assert.deepEqual(_.filter(list, {}), list, 'Empty object accepts all items'); assert.deepEqual(_(list).filter({}), list, 'OO-filter'); }); QUnit.test('select', function(assert) { assert.strictEqual(_.select, _.filter, 'is an alias for filter'); }); QUnit.test('reject', function(assert) { var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 === 0; }); assert.deepEqual(odds, [1, 3, 5], 'rejected each even number'); var context = 'obj'; var evens = _.reject([1, 2, 3, 4, 5, 6], function(num){ assert.strictEqual(context, 'obj'); return num % 2 !== 0; }, context); assert.deepEqual(evens, [2, 4, 6], 'rejected each odd number'); assert.deepEqual(_.reject([odds, {one: 1, two: 2, three: 3}], 'two'), [odds], 'predicate string map to object properties'); // Can be used like _.where. var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}]; assert.deepEqual(_.reject(list, {a: 1}), [{a: 2, b: 2}]); assert.deepEqual(_.reject(list, {b: 2}), [{a: 1, b: 3}, {a: 1, b: 4}]); assert.deepEqual(_.reject(list, {}), [], 'Returns empty list given empty object'); }); QUnit.test('every', function(assert) { assert.ok(_.every([], _.identity), 'the empty set'); assert.ok(_.every([true, true, true], _.identity), 'every true values'); assert.ok(!_.every([true, false, true], _.identity), 'one false value'); assert.ok(_.every([0, 10, 28], function(num){ return num % 2 === 0; }), 'even numbers'); assert.ok(!_.every([0, 11, 28], function(num){ return num % 2 === 0; }), 'an odd number'); assert.strictEqual(_.every([1], _.identity), true, 'cast to boolean - true'); assert.strictEqual(_.every([0], _.identity), false, 'cast to boolean - false'); assert.ok(!_.every([void 0, void 0, void 0], _.identity), 'works with arrays of undefined'); var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}]; assert.ok(!_.every(list, {a: 1, b: 2}), 'Can be called with object'); assert.ok(_.every(list, 'a'), 'String mapped to object property'); list = [{a: 1, b: 2}, {a: 2, b: 2, c: true}]; assert.ok(_.every(list, {b: 2}), 'Can be called with object'); assert.ok(!_.every(list, 'c'), 'String mapped to object property'); assert.ok(_.every({a: 1, b: 2, c: 3, d: 4}, _.isNumber), 'takes objects'); assert.ok(!_.every({a: 1, b: 2, c: 3, d: 4}, _.isObject), 'takes objects'); assert.ok(_.every(['a', 'b', 'c', 'd'], _.hasOwnProperty, {a: 1, b: 2, c: 3, d: 4}), 'context works'); assert.ok(!_.every(['a', 'b', 'c', 'd', 'f'], _.hasOwnProperty, {a: 1, b: 2, c: 3, d: 4}), 'context works'); }); QUnit.test('all', function(assert) { assert.strictEqual(_.all, _.every, 'is an alias for every'); }); QUnit.test('some', function(assert) { assert.ok(!_.some([]), 'the empty set'); assert.ok(!_.some([false, false, false]), 'all false values'); assert.ok(_.some([false, false, true]), 'one true value'); assert.ok(_.some([null, 0, 'yes', false]), 'a string'); assert.ok(!_.some([null, 0, '', false]), 'falsy values'); assert.ok(!_.some([1, 11, 29], function(num){ return num % 2 === 0; }), 'all odd numbers'); assert.ok(_.some([1, 10, 29], function(num){ return num % 2 === 0; }), 'an even number'); assert.strictEqual(_.some([1], _.identity), true, 'cast to boolean - true'); assert.strictEqual(_.some([0], _.identity), false, 'cast to boolean - false'); assert.ok(_.some([false, false, true])); var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}]; assert.ok(!_.some(list, {a: 5, b: 2}), 'Can be called with object'); assert.ok(_.some(list, 'a'), 'String mapped to object property'); list = [{a: 1, b: 2}, {a: 2, b: 2, c: true}]; assert.ok(_.some(list, {b: 2}), 'Can be called with object'); assert.ok(!_.some(list, 'd'), 'String mapped to object property'); assert.ok(_.some({a: '1', b: '2', c: '3', d: '4', e: 6}, _.isNumber), 'takes objects'); assert.ok(!_.some({a: 1, b: 2, c: 3, d: 4}, _.isObject), 'takes objects'); assert.ok(_.some(['a', 'b', 'c', 'd'], _.hasOwnProperty, {a: 1, b: 2, c: 3, d: 4}), 'context works'); assert.ok(!_.some(['x', 'y', 'z'], _.hasOwnProperty, {a: 1, b: 2, c: 3, d: 4}), 'context works'); }); QUnit.test('any', function(assert) { assert.strictEqual(_.any, _.some, 'is an alias for some'); }); QUnit.test('includes', function(assert) { _.each([null, void 0, 0, 1, NaN, {}, []], function(val) { assert.strictEqual(_.includes(val, 'hasOwnProperty'), false); }); assert.strictEqual(_.includes([1, 2, 3], 2), true, 'two is in the array'); assert.ok(!_.includes([1, 3, 9], 2), 'two is not in the array'); assert.strictEqual(_.includes([5, 4, 3, 2, 1], 5, true), true, 'doesn\'t delegate to binary search'); assert.strictEqual(_.includes({moe: 1, larry: 3, curly: 9}, 3), true, '_.includes on objects checks their values'); assert.ok(_([1, 2, 3]).includes(2), 'OO-style includes'); var numbers = [1, 2, 3, 1, 2, 3, 1, 2, 3]; assert.strictEqual(_.includes(numbers, 1, 1), true, 'takes a fromIndex'); assert.strictEqual(_.includes(numbers, 1, -1), false, 'takes a fromIndex'); assert.strictEqual(_.includes(numbers, 1, -2), false, 'takes a fromIndex'); assert.strictEqual(_.includes(numbers, 1, -3), true, 'takes a fromIndex'); assert.strictEqual(_.includes(numbers, 1, 6), true, 'takes a fromIndex'); assert.strictEqual(_.includes(numbers, 1, 7), false, 'takes a fromIndex'); assert.ok(_.every([1, 2, 3], _.partial(_.includes, numbers)), 'fromIndex is guarded'); }); QUnit.test('include', function(assert) { assert.strictEqual(_.include, _.includes, 'is an alias for includes'); }); QUnit.test('contains', function(assert) { assert.strictEqual(_.contains, _.includes, 'is an alias for includes'); }); QUnit.test('includes with NaN', function(assert) { assert.strictEqual(_.includes([1, 2, NaN, NaN], NaN), true, 'Expected [1, 2, NaN] to contain NaN'); assert.strictEqual(_.includes([1, 2, Infinity], NaN), false, 'Expected [1, 2, Infinity] to NOT contain NaN'); }); QUnit.test('includes with +- 0', function(assert) { _.each([-0, +0], function(val) { assert.strictEqual(_.includes([1, 2, val, val], val), true); assert.strictEqual(_.includes([1, 2, val, val], -val), true); assert.strictEqual(_.includes([-1, 1, 2], -val), false); }); }); QUnit.test('invoke', function(assert) { assert.expect(13); var list = [[5, 1, 7], [3, 2, 1]]; var result = _.invoke(list, 'sort'); assert.deepEqual(result[0], [1, 5, 7], 'first array sorted'); assert.deepEqual(result[1], [1, 2, 3], 'second array sorted'); _.invoke([{ method: function() { assert.deepEqual(_.toArray(arguments), [1, 2, 3], 'called with arguments'); } }], 'method', 1, 2, 3); assert.deepEqual(_.invoke([{a: null}, {}, {a: _.constant(1)}], 'a'), [null, void 0, 1], 'handles null & undefined'); assert.raises(function() { _.invoke([{a: 1}], 'a'); }, TypeError, 'throws for non-functions'); var getFoo = _.constant('foo'); var getThis = function() { return this; }; var item = { a: { b: getFoo, c: getThis, d: null }, e: getFoo, f: getThis, g: function() { return { h: getFoo }; } }; var arr = [item]; assert.deepEqual(_.invoke(arr, ['a', 'b']), ['foo'], 'supports deep method access via an array syntax'); assert.deepEqual(_.invoke(arr, ['a', 'c']), [item.a], 'executes deep methods on their direct parent'); assert.deepEqual(_.invoke(arr, ['a', 'd', 'z']), [void 0], 'does not try to access attributes of non-objects'); assert.deepEqual(_.invoke(arr, ['a', 'd']), [null], 'handles deep null values'); assert.deepEqual(_.invoke(arr, ['e']), ['foo'], 'handles path arrays of length one'); assert.deepEqual(_.invoke(arr, ['f']), [item], 'correct uses parent context with shallow array syntax'); assert.deepEqual(_.invoke(arr, ['g', 'h']), [void 0], 'does not execute intermediate functions'); arr = [{ a: function() { return 'foo'; } }, { a: function() { return 'bar'; } }]; assert.deepEqual(_.invoke(arr, 'a'), ['foo', 'bar'], 'can handle different methods on subsequent objects'); }); QUnit.test('invoke w/ function reference', function(assert) { var list = [[5, 1, 7], [3, 2, 1]]; var result = _.invoke(list, Array.prototype.sort); assert.deepEqual(result[0], [1, 5, 7], 'first array sorted'); assert.deepEqual(result[1], [1, 2, 3], 'second array sorted'); assert.deepEqual(_.invoke([1, 2, 3], function(a) { return a + this; }, 5), [6, 7, 8], 'receives params from invoke'); }); // Relevant when using ClojureScript QUnit.test('invoke when strings have a call method', function(assert) { String.prototype.call = function() { return 42; }; var list = [[5, 1, 7], [3, 2, 1]]; var s = 'foo'; assert.strictEqual(s.call(), 42, 'call function exists'); var result = _.invoke(list, 'sort'); assert.deepEqual(result[0], [1, 5, 7], 'first array sorted'); assert.deepEqual(result[1], [1, 2, 3], 'second array sorted'); delete String.prototype.call; assert.strictEqual(s.call, void 0, 'call function removed'); }); QUnit.test('pluck', function(assert) { var people = [{name: 'moe', age: 30}, {name: 'curly', age: 50}]; assert.deepEqual(_.pluck(people, 'name'), ['moe', 'curly'], 'pulls names out of objects'); assert.deepEqual(_.pluck(people, 'address'), [void 0, void 0], 'missing properties are returned as undefined'); //compat: most flexible handling of edge cases assert.deepEqual(_.pluck([{'[object Object]': 1}], {}), [1]); }); QUnit.test('where', function(assert) { var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}]; var result = _.where(list, {a: 1}); assert.strictEqual(result.length, 3); assert.strictEqual(result[result.length - 1].b, 4); result = _.where(list, {b: 2}); assert.strictEqual(result.length, 2); assert.strictEqual(result[0].a, 1); result = _.where(list, {}); assert.strictEqual(result.length, list.length); function test() {} test.map = _.map; assert.deepEqual(_.where([_, {a: 1, b: 2}, _], test), [_, _], 'checks properties given function'); }); QUnit.test('findWhere', function(assert) { var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}, {a: 2, b: 4}]; var result = _.findWhere(list, {a: 1}); assert.deepEqual(result, {a: 1, b: 2}); result = _.findWhere(list, {b: 4}); assert.deepEqual(result, {a: 1, b: 4}); result = _.findWhere(list, {c: 1}); assert.ok(_.isUndefined(result), 'undefined when not found'); result = _.findWhere([], {c: 1}); assert.ok(_.isUndefined(result), 'undefined when searching empty list'); function test() {} test.map = _.map; assert.strictEqual(_.findWhere([_, {a: 1, b: 2}, _], test), _, 'checks properties given function'); function TestClass() { this.y = 5; this.x = 'foo'; } var expect = {c: 1, x: 'foo', y: 5}; assert.deepEqual(_.findWhere([{y: 5, b: 6}, expect], new TestClass()), expect, 'uses class instance properties'); }); QUnit.test('max', function(assert) { assert.strictEqual(_.max(null), -Infinity, 'can handle null/undefined'); assert.strictEqual(_.max(void 0), -Infinity, 'can handle null/undefined'); assert.strictEqual(_.max(null, _.identity), -Infinity, 'can handle null/undefined'); assert.strictEqual(_.max([1, 2, 3]), 3, 'can perform a regular Math.max'); var neg = _.max([1, 2, 3], function(num){ return -num; }); assert.strictEqual(neg, 1, 'can perform a computation-based max'); assert.strictEqual(_.max({}), -Infinity, 'Maximum value of an empty object'); assert.strictEqual(_.max([]), -Infinity, 'Maximum value of an empty array'); assert.strictEqual(_.max({a: 'a'}), -Infinity, 'Maximum value of a non-numeric collection'); assert.strictEqual(_.max(_.range(1, 300000)), 299999, 'Maximum value of a too-big array'); assert.strictEqual(_.max([1, 2, 3, 'test']), 3, 'Finds correct max in array starting with num and containing a NaN'); assert.strictEqual(_.max(['test', 1, 2, 3]), 3, 'Finds correct max in array starting with NaN'); assert.strictEqual(_.max([1, 2, 3, null]), 3, 'Finds correct max in array starting with num and containing a `null`'); assert.strictEqual(_.max([null, 1, 2, 3]), 3, 'Finds correct max in array starting with a `null`'); assert.strictEqual(_.max([1, 2, 3, '']), 3, 'Finds correct max in array starting with num and containing an empty string'); assert.strictEqual(_.max(['', 1, 2, 3]), 3, 'Finds correct max in array starting with an empty string'); assert.strictEqual(_.max([1, 2, 3, false]), 3, 'Finds correct max in array starting with num and containing a false'); assert.strictEqual(_.max([false, 1, 2, 3]), 3, 'Finds correct max in array starting with a false'); assert.strictEqual(_.max([0, 1, 2, 3, 4]), 4, 'Finds correct max in array containing a zero'); assert.strictEqual(_.max([-3, -2, -1, 0]), 0, 'Finds correct max in array containing negative numbers'); assert.deepEqual(_.map([[1, 2, 3], [4, 5, 6]], _.max), [3, 6], 'Finds correct max in array when mapping through multiple arrays'); var a = {x: -Infinity}; var b = {x: -Infinity}; var iterator = function(o){ return o.x; }; assert.strictEqual(_.max([a, b], iterator), a, 'Respects iterator return value of -Infinity'); assert.deepEqual(_.max([{a: 1}, {a: 0, b: 3}, {a: 4}, {a: 2}], 'a'), {a: 4}, 'String keys use property iterator'); assert.deepEqual(_.max([0, 2], function(c){ return c * this.x; }, {x: 1}), 2, 'Iterator context'); assert.deepEqual(_.max([[1], [2, 3], [-1, 4], [5]], 0), [5], 'Lookup falsy iterator'); assert.deepEqual(_.max([{0: 1}, {0: 2}, {0: -1}, {a: 1}], 0), {0: 2}, 'Lookup falsy iterator'); }); QUnit.test('min', function(assert) { assert.strictEqual(_.min(null), Infinity, 'can handle null/undefined'); assert.strictEqual(_.min(void 0), Infinity, 'can handle null/undefined'); assert.strictEqual(_.min(null, _.identity), Infinity, 'can handle null/undefined'); assert.strictEqual(_.min([1, 2, 3]), 1, 'can perform a regular Math.min'); var neg = _.min([1, 2, 3], function(num){ return -num; }); assert.strictEqual(neg, 3, 'can perform a computation-based min'); assert.strictEqual(_.min({}), Infinity, 'Minimum value of an empty object'); assert.strictEqual(_.min([]), Infinity, 'Minimum value of an empty array'); assert.strictEqual(_.min({a: 'a'}), Infinity, 'Minimum value of a non-numeric collection'); assert.deepEqual(_.map([[1, 2, 3], [4, 5, 6]], _.min), [1, 4], 'Finds correct min in array when mapping through multiple arrays'); var now = new Date(9999999999); var then = new Date(0); assert.strictEqual(_.min([now, then]), then); assert.strictEqual(_.min(_.range(1, 300000)), 1, 'Minimum value of a too-big array'); assert.strictEqual(_.min([1, 2, 3, 'test']), 1, 'Finds correct min in array starting with num and containing a NaN'); assert.strictEqual(_.min(['test', 1, 2, 3]), 1, 'Finds correct min in array starting with NaN'); assert.strictEqual(_.min([1, 2, 3, null]), 1, 'Finds correct min in array starting with num and containing a `null`'); assert.strictEqual(_.min([null, 1, 2, 3]), 1, 'Finds correct min in array starting with a `null`'); assert.strictEqual(_.min([0, 1, 2, 3, 4]), 0, 'Finds correct min in array containing a zero'); assert.strictEqual(_.min([-3, -2, -1, 0]), -3, 'Finds correct min in array containing negative numbers'); var a = {x: Infinity}; var b = {x: Infinity}; var iterator = function(o){ return o.x; }; assert.strictEqual(_.min([a, b], iterator), a, 'Respects iterator return value of Infinity'); assert.deepEqual(_.min([{a: 1}, {a: 0, b: 3}, {a: 4}, {a: 2}], 'a'), {a: 0, b: 3}, 'String keys use property iterator'); assert.deepEqual(_.min([0, 2], function(c){ return c * this.x; }, {x: -1}), 2, 'Iterator context'); assert.deepEqual(_.min([[1], [2, 3], [-1, 4], [5]], 0), [-1, 4], 'Lookup falsy iterator'); assert.deepEqual(_.min([{0: 1}, {0: 2}, {0: -1}, {a: 1}], 0), {0: -1}, 'Lookup falsy iterator'); }); QUnit.test('sortBy', function(assert) { var people = [{name: 'curly', age: 50}, {name: 'moe', age: 30}]; people = _.sortBy(people, function(person){ return person.age; }); assert.deepEqual(_.pluck(people, 'name'), ['moe', 'curly'], 'stooges sorted by age'); var list = [void 0, 4, 1, void 0, 3, 2]; assert.deepEqual(_.sortBy(list, _.identity), [1, 2, 3, 4, void 0, void 0], 'sortBy with undefined values'); list = ['one', 'two', 'three', 'four', 'five']; var sorted = _.sortBy(list, 'length'); assert.deepEqual(sorted, ['one', 'two', 'four', 'five', 'three'], 'sorted by length'); function Pair(x, y) { this.x = x; this.y = y; } var stableArray = [ new Pair(1, 1), new Pair(1, 2), new Pair(1, 3), new Pair(1, 4), new Pair(1, 5), new Pair(1, 6), new Pair(2, 1), new Pair(2, 2), new Pair(2, 3), new Pair(2, 4), new Pair(2, 5), new Pair(2, 6), new Pair(void 0, 1), new Pair(void 0, 2), new Pair(void 0, 3), new Pair(void 0, 4), new Pair(void 0, 5), new Pair(void 0, 6) ]; var stableObject = _.object('abcdefghijklmnopqr'.split(''), stableArray); var actual = _.sortBy(stableArray, function(pair) { return pair.x; }); assert.deepEqual(actual, stableArray, 'sortBy should be stable for arrays'); assert.deepEqual(_.sortBy(stableArray, 'x'), stableArray, 'sortBy accepts property string'); actual = _.sortBy(stableObject, function(pair) { return pair.x; }); assert.deepEqual(actual, stableArray, 'sortBy should be stable for objects'); list = ['q', 'w', 'e', 'r', 't', 'y']; assert.deepEqual(_.sortBy(list), ['e', 'q', 'r', 't', 'w', 'y'], 'uses _.identity if iterator is not specified'); }); QUnit.test('groupBy', function(assert) { var parity = _.groupBy([1, 2, 3, 4, 5, 6], function(num){ return num % 2; }); assert.ok('0' in parity && '1' in parity, 'created a group for each value'); assert.deepEqual(parity[0], [2, 4, 6], 'put each even number in the right group'); var list = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']; var grouped = _.groupBy(list, 'length'); assert.deepEqual(grouped['3'], ['one', 'two', 'six', 'ten']); assert.deepEqual(grouped['4'], ['four', 'five', 'nine']); assert.deepEqual(grouped['5'], ['three', 'seven', 'eight']); var context = {}; _.groupBy([{}], function(){ assert.strictEqual(this, context); }, context); grouped = _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor'; }); assert.strictEqual(grouped.constructor.length, 1); assert.strictEqual(grouped.hasOwnProperty.length, 2); var array = [{}]; _.groupBy(array, function(value, index, obj){ assert.strictEqual(obj, array); }); array = [1, 2, 1, 2, 3]; grouped = _.groupBy(array); assert.strictEqual(grouped['1'].length, 2); assert.strictEqual(grouped['3'].length, 1); var matrix = [ [1, 2], [1, 3], [2, 3] ]; assert.deepEqual(_.groupBy(matrix, 0), {1: [[1, 2], [1, 3]], 2: [[2, 3]]}); assert.deepEqual(_.groupBy(matrix, 1), {2: [[1, 2]], 3: [[1, 3], [2, 3]]}); var liz = {name: 'Liz', stats: {power: 10}}; var chelsea = {name: 'Chelsea', stats: {power: 10}}; var jordan = {name: 'Jordan', stats: {power: 6}}; var collection = [liz, chelsea, jordan]; var expected = { 10: [liz, chelsea], 6: [jordan] }; assert.deepEqual(_.groupBy(collection, ['stats', 'power']), expected, 'can group by deep properties'); var foos = [{foo: [1, 2]}, {foo: [1, 2]}] assert.deepEqual(_.groupBy(foos, 'foo'), {"1,2": foos}, 'will coerce arrays to string keys'); }); QUnit.test('indexBy', function(assert) { var parity = _.indexBy([1, 2, 3, 4, 5], function(num){ return num % 2 === 0; }); assert.strictEqual(parity['true'], 4); assert.strictEqual(parity['false'], 5); var list = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']; var grouped = _.indexBy(list, 'length'); assert.strictEqual(grouped['3'], 'ten'); assert.strictEqual(grouped['4'], 'nine'); assert.strictEqual(grouped['5'], 'eight'); var array = [1, 2, 1, 2, 3]; grouped = _.indexBy(array); assert.strictEqual(grouped['1'], 1); assert.strictEqual(grouped['2'], 2); assert.strictEqual(grouped['3'], 3); }); QUnit.test('countBy', function(assert) { var parity = _.countBy([1, 2, 3, 4, 5], function(num){ return num % 2 === 0; }); assert.strictEqual(parity['true'], 2); assert.strictEqual(parity['false'], 3); var list = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']; var grouped = _.countBy(list, 'length'); assert.strictEqual(grouped['3'], 4); assert.strictEqual(grouped['4'], 3); assert.strictEqual(grouped['5'], 3); var context = {}; _.countBy([{}], function(){ assert.strictEqual(this, context); }, context); grouped = _.countBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor'; }); assert.strictEqual(grouped.constructor, 1); assert.strictEqual(grouped.hasOwnProperty, 2); var array = [{}]; _.countBy(array, function(value, index, obj){ assert.strictEqual(obj, array); }); array = [1, 2, 1, 2, 3]; grouped = _.countBy(array); assert.strictEqual(grouped['1'], 2); assert.strictEqual(grouped['3'], 1); var foos = [{foo: [1, 2]}, {foo: [1, 2]}] assert.deepEqual(_.countBy(foos, 'foo'), {'1,2': 2}, 'will coerce arrays to string keys'); }); QUnit.test('shuffle', function(assert) { assert.deepEqual(_.shuffle([1]), [1], 'behaves correctly on size 1 arrays'); var numbers = _.range(20); var shuffled = _.shuffle(numbers); assert.notDeepEqual(numbers, shuffled, 'does change the order'); // Chance of false negative: 1 in ~2.4*10^18 assert.notStrictEqual(numbers, shuffled, 'original object is unmodified'); assert.deepEqual(numbers, _.sortBy(shuffled), 'contains the same members before and after shuffle'); shuffled = _.shuffle({a: 1, b: 2, c: 3, d: 4}); assert.strictEqual(shuffled.length, 4); assert.deepEqual(shuffled.sort(), [1, 2, 3, 4], 'works on objects'); }); QUnit.test('sample', function(assert) { assert.strictEqual(_.sample([1]), 1, 'behaves correctly when no second parameter is given'); assert.deepEqual(_.sample([1, 2, 3], -2), [], 'behaves correctly on negative n'); var numbers = _.range(10); var allSampled = _.sample(numbers, 10).sort(); assert.deepEqual(allSampled, numbers, 'contains the same members before and after sample'); allSampled = _.sample(numbers, 20).sort(); assert.deepEqual(allSampled, numbers, 'also works when sampling more objects than are present'); assert.ok(_.contains(numbers, _.sample(numbers)), 'sampling a single element returns something from the array'); assert.strictEqual(_.sample([]), void 0, 'sampling empty array with no number returns undefined'); assert.notStrictEqual(_.sample([], 5), [], 'sampling empty array with a number returns an empty array'); assert.notStrictEqual(_.sample([1, 2, 3], 0), [], 'sampling an array with 0 picks returns an empty array'); assert.deepEqual(_.sample([1, 2], -1), [], 'sampling a negative number of picks returns an empty array'); assert.ok(_.contains([1, 2, 3], _.sample({a: 1, b: 2, c: 3})), 'sample one value from an object'); var partialSample = _.sample(_.range(1000), 10); var partialSampleSorted = partialSample.sort(); assert.notDeepEqual(partialSampleSorted, _.range(10), 'samples from the whole array, not just the beginning'); // The next few lines (up to END) are a regression test for #2927. var alphabet = 'abcdefghijklmnopqrstuvwxyz'; var prefixLength = 5; var prefix = _.toArray(alphabet.slice(0, prefixLength)); // We're going to take three random samples from the alphabet and count how // many of them are exact prefixes of the alphabet ('abcde'). var verbatimPrefixes = 0; _.times(3, function() { var sample = _.toArray(_.sample(alphabet, prefixLength)); if (_.isEqual(sample, prefix)) ++verbatimPrefixes; }); // The probability of a sample of length N being a prefix is 1/(A!/(A-N)!), // with A being the length of the alphabet. That amounts to roughly 1 in // 7.9e6 when N=5 and A=26. Most of the time, therefore, we should find that // verbatimPrefixes=0. We will however accept the occasional hit. Only when // it happens twice, does it start to look really suspicious; the // probability of this happening is roughly 1 in 21e12. If you are lucky // enough to witness this, you should be fine when you run the test again. // However, if you can reliably make the test fail again, you can be sure // that the code is not working as intended. assert.ok(verbatimPrefixes < 2, 'sampling a string should not just return a prefix'); // END of regression test for #2927. }); QUnit.test('toArray', function(assert) { assert.ok(!_.isArray(arguments), 'arguments object is not an array'); assert.ok(_.isArray(_.toArray(arguments)), 'arguments object converted into array'); var a = [1, 2, 3]; assert.notStrictEqual(_.toArray(a), a, 'array is cloned'); assert.deepEqual(_.toArray(a), [1, 2, 3], 'cloned array contains same elements'); var numbers = _.toArray({one: 1, two: 2, three: 3}); assert.deepEqual(numbers, [1, 2, 3], 'object flattened into array'); var hearts = '\uD83D\uDC95'; var pair = hearts.split(''); var expected = [pair[0], hearts, '&', hearts, pair[1]]; assert.deepEqual(_.toArray(expected.join('')), expected, 'maintains astral characters'); assert.deepEqual(_.toArray(''), [], 'empty string into empty array'); if (typeof document != 'undefined') { // test in IE < 9 var actual; try { actual = _.toArray(document.childNodes); } catch (e) { /* ignored */ } assert.deepEqual(actual, _.map(document.childNodes, _.identity), 'works on NodeList'); } }); QUnit.test('size', function(assert) { assert.strictEqual(_.size({one: 1, two: 2, three: 3}), 3, 'can compute the size of an object'); assert.strictEqual(_.size([1, 2, 3]), 3, 'can compute the size of an array'); assert.strictEqual(_.size({length: 3, 0: 0, 1: 0, 2: 0}), 3, 'can compute the size of Array-likes'); var func = function() { return _.size(arguments); }; assert.strictEqual(func(1, 2, 3, 4), 4, 'can test the size of the arguments object'); assert.strictEqual(_.size('hello'), 5, 'can compute the size of a string literal'); assert.strictEqual(_.size(new String('hello')), 5, 'can compute the size of string object'); assert.strictEqual(_.size(null), 0, 'handles nulls'); assert.strictEqual(_.size(0), 0, 'handles numbers'); }); QUnit.test('partition', function(assert) { var list = [0, 1, 2, 3, 4, 5]; assert.deepEqual(_.partition(list, function(x) { return x < 4; }), [[0, 1, 2, 3], [4, 5]], 'handles bool return values'); assert.deepEqual(_.partition(list, function(x) { return x & 1; }), [[1, 3, 5], [0, 2, 4]], 'handles 0 and 1 return values'); assert.deepEqual(_.partition(list, function(x) { return x - 3; }), [[0, 1, 2, 4, 5], [3]], 'handles other numeric return values'); assert.deepEqual(_.partition(list, function(x) { return x > 1 ? null : true; }), [[0, 1], [2, 3, 4, 5]], 'handles null return values'); assert.deepEqual(_.partition(list, function(x) { if (x < 2) return true; }), [[0, 1], [2, 3, 4, 5]], 'handles undefined return values'); assert.deepEqual(_.partition({a: 1, b: 2, c: 3}, function(x) { return x > 1; }), [[2, 3], [1]], 'handles objects'); assert.deepEqual(_.partition(list, function(x, index) { return index % 2; }), [[1, 3, 5], [0, 2, 4]], 'can reference the array index'); assert.deepEqual(_.partition(list, function(x, index, arr) { return x === arr.length - 1; }), [[5], [0, 1, 2, 3, 4]], 'can reference the collection'); // Default iterator assert.deepEqual(_.partition([1, false, true, '']), [[1, true], [false, '']], 'Default iterator'); assert.deepEqual(_.partition([{x: 1}, {x: 0}, {x: 1}], 'x'), [[{x: 1}, {x: 1}], [{x: 0}]], 'Takes a string'); // Context var predicate = function(x){ return x === this.x; }; assert.deepEqual(_.partition([1, 2, 3], predicate, {x: 2}), [[2], [1, 3]], 'partition takes a context argument'); assert.deepEqual(_.partition([{a: 1}, {b: 2}, {a: 1, b: 2}], {a: 1}), [[{a: 1}, {a: 1, b: 2}], [{b: 2}]], 'predicate can be object'); var object = {a: 1}; _.partition(object, function(val, key, obj) { assert.strictEqual(val, 1); assert.strictEqual(key, 'a'); assert.strictEqual(obj, object); assert.strictEqual(this, predicate); }, predicate); }); if (typeof document != 'undefined') { QUnit.test('Can use various collection methods on NodeLists', function(assert) { var parent = document.createElement('div'); parent.innerHTML = 'textnode'; var elementChildren = _.filter(parent.childNodes, _.isElement); assert.strictEqual(elementChildren.length, 2); assert.deepEqual(_.map(elementChildren, 'id'), ['id1', 'id2']); assert.deepEqual(_.map(parent.childNodes, 'nodeType'), [1, 3, 1]); assert.ok(!_.every(parent.childNodes, _.isElement)); assert.ok(_.some(parent.childNodes, _.isElement)); function compareNode(node) { return _.isElement(node) ? node.id.charAt(2) : void 0; } assert.strictEqual(_.max(parent.childNodes, compareNode), _.last(parent.childNodes)); assert.strictEqual(_.min(parent.childNodes, compareNode), _.first(parent.childNodes)); }); } }()); ================================================ FILE: test/cross-document.js ================================================ (function() { if (typeof document == 'undefined') return; var _ = typeof require == 'function' ? require('..') : window._; QUnit.module('Cross Document'); /* global iObject, iElement, iArguments, iFunction, iArray, iError, iString, iNumber, iBoolean, iDate, iRegExp, iNaN, iNull, iUndefined, ActiveXObject */ // Setup remote variables for iFrame tests. var iframe = document.createElement('iframe'); iframe.frameBorder = iframe.height = iframe.width = 0; document.body.appendChild(iframe); var iframeContent = iframe.contentDocument || iframe.contentWindow; var iDoc = iframeContent.document || iframeContent; iDoc.write( [ '' ].join('\n') ); iDoc.close(); QUnit.test('isEqual', function(assert) { assert.ok(!_.isEqual(iNumber, 101)); assert.ok(_.isEqual(iNumber, 100)); // Objects from another frame. assert.ok(_.isEqual({}, iObject), 'Objects with equivalent members created in different documents are equal'); // Array from another frame. assert.ok(_.isEqual([1, 2, 3], iArray), 'Arrays with equivalent elements created in different documents are equal'); }); QUnit.test('isEmpty', function(assert) { assert.ok(!_([iNumber]).isEmpty(), '[1] is not empty'); assert.ok(!_.isEmpty(iArray), '[] is empty'); assert.ok(_.isEmpty(iObject), '{} is empty'); }); QUnit.test('isElement', function(assert) { assert.ok(!_.isElement('div'), 'strings are not dom elements'); assert.ok(_.isElement(document.body), 'the body tag is a DOM element'); assert.ok(_.isElement(iElement), 'even from another frame'); }); QUnit.test('isArguments', function(assert) { assert.ok(_.isArguments(iArguments), 'even from another frame'); }); QUnit.test('isObject', function(assert) { assert.ok(_.isObject(iElement), 'even from another frame'); assert.ok(_.isObject(iFunction), 'even from another frame'); }); QUnit.test('isArray', function(assert) { assert.ok(_.isArray(iArray), 'even from another frame'); }); QUnit.test('isString', function(assert) { assert.ok(_.isString(iString), 'even from another frame'); }); QUnit.test('isNumber', function(assert) { assert.ok(_.isNumber(iNumber), 'even from another frame'); }); QUnit.test('isBoolean', function(assert) { assert.ok(_.isBoolean(iBoolean), 'even from another frame'); }); QUnit.test('isFunction', function(assert) { assert.ok(_.isFunction(iFunction), 'even from another frame'); }); QUnit.test('isDate', function(assert) { assert.ok(_.isDate(iDate), 'even from another frame'); }); QUnit.test('isRegExp', function(assert) { assert.ok(_.isRegExp(iRegExp), 'even from another frame'); }); QUnit.test('isNaN', function(assert) { assert.ok(_.isNaN(iNaN), 'even from another frame'); }); QUnit.test('isNull', function(assert) { assert.ok(_.isNull(iNull), 'even from another frame'); }); QUnit.test('isUndefined', function(assert) { assert.ok(_.isUndefined(iUndefined), 'even from another frame'); }); QUnit.test('isError', function(assert) { assert.ok(_.isError(iError), 'even from another frame'); }); if (typeof ActiveXObject != 'undefined') { QUnit.test('IE host objects', function(assert) { var xml = new ActiveXObject('Msxml2.DOMDocument.3.0'); assert.ok(!_.isNumber(xml)); assert.ok(!_.isBoolean(xml)); assert.ok(!_.isNaN(xml)); assert.ok(!_.isFunction(xml)); assert.ok(!_.isNull(xml)); assert.ok(!_.isUndefined(xml)); }); QUnit.test('#1621 IE 11 compat mode DOM elements are not functions', function(assert) { var fn = function() {}; var xml = new ActiveXObject('Msxml2.DOMDocument.3.0'); var div = document.createElement('div'); // JIT the function var count = 200; while (count--) { _.isFunction(fn); } assert.strictEqual(_.isFunction(xml), false); assert.strictEqual(_.isFunction(div), false); assert.strictEqual(_.isFunction(fn), true); }); } }()); ================================================ FILE: test/functions.js ================================================ (function() { var _ = typeof require == 'function' ? require('..') : window._; QUnit.module('Functions'); QUnit.config.asyncRetries = 3; QUnit.test('bind', function(assert) { var context = {name: 'moe'}; var func = function(arg) { return 'name: ' + (this.name || arg); }; var bound = _.bind(func, context); assert.strictEqual(bound(), 'name: moe', 'can bind a function to a context'); bound = _(func).bind(context); assert.strictEqual(bound(), 'name: moe', 'can do OO-style binding'); bound = _.bind(func, null, 'curly'); var result = bound(); // Work around a PhantomJS bug when applying a function with null|undefined. assert.ok(result === 'name: curly' || result === 'name: ' + window.name, 'can bind without specifying a context'); func = function(salutation, name) { return salutation + ': ' + name; }; func = _.bind(func, this, 'hello'); assert.strictEqual(func('moe'), 'hello: moe', 'the function was partially applied in advance'); func = _.bind(func, this, 'curly'); assert.strictEqual(func(), 'hello: curly', 'the function was completely applied in advance'); func = function(salutation, firstname, lastname) { return salutation + ': ' + firstname + ' ' + lastname; }; func = _.bind(func, this, 'hello', 'moe', 'curly'); assert.strictEqual(func(), 'hello: moe curly', 'the function was partially applied in advance and can accept multiple arguments'); func = function() { return this; }; assert.strictEqual(typeof _.bind(func, 0)(), 'object', 'binding a primitive to `this` returns a wrapped primitive'); assert.strictEqual(_.bind(func, 0)().valueOf(), 0, 'can bind a function to `0`'); assert.strictEqual(_.bind(func, '')().valueOf(), '', 'can bind a function to an empty string'); assert.strictEqual(_.bind(func, false)().valueOf(), false, 'can bind a function to `false`'); // These tests are only meaningful when using a browser without a native bind function // To test this with a modern browser, set underscore's nativeBind to undefined var F = function() { return this; }; var boundf = _.bind(F, {hello: 'moe curly'}); var Boundf = boundf; // make eslint happy. var newBoundf = new Boundf(); assert.strictEqual(newBoundf.hello, void 0, 'function should not be bound to the context, to comply with ECMAScript 5'); assert.strictEqual(boundf().hello, 'moe curly', "When called without the new operator, it's OK to be bound to the context"); assert.ok(newBoundf instanceof F, 'a bound instance is an instance of the original function'); assert.raises(function() { _.bind('notafunction'); }, TypeError, 'throws an error when binding to a non-function'); }); QUnit.test('partial', function(assert) { var obj = {name: 'moe'}; var func = function() { return this.name + ' ' + _.toArray(arguments).join(' '); }; obj.func = _.partial(func, 'a', 'b'); assert.strictEqual(obj.func('c', 'd'), 'moe a b c d', 'can partially apply'); obj.func = _.partial(func, _, 'b', _, 'd'); assert.strictEqual(obj.func('a', 'c'), 'moe a b c d', 'can partially apply with placeholders'); func = _.partial(function() { return arguments.length; }, _, 'b', _, 'd'); assert.strictEqual(func('a', 'c', 'e'), 5, 'accepts more arguments than the number of placeholders'); assert.strictEqual(func('a'), 4, 'accepts fewer arguments than the number of placeholders'); func = _.partial(function() { return typeof arguments[2]; }, _, 'b', _, 'd'); assert.strictEqual(func('a'), 'undefined', 'unfilled placeholders are undefined'); // passes context function MyWidget(name, options) { this.name = name; this.options = options; } MyWidget.prototype.get = function() { return this.name; }; var MyWidgetWithCoolOpts = _.partial(MyWidget, _, {a: 1}); var widget = new MyWidgetWithCoolOpts('foo'); assert.ok(widget instanceof MyWidget, 'Can partially bind a constructor'); assert.strictEqual(widget.get(), 'foo', 'keeps prototype'); assert.deepEqual(widget.options, {a: 1}); _.partial.placeholder = obj; func = _.partial(function() { return arguments.length; }, obj, 'b', obj, 'd'); assert.strictEqual(func('a'), 4, 'allows the placeholder to be swapped out'); _.partial.placeholder = {}; func = _.partial(function() { return arguments.length; }, obj, 'b', obj, 'd'); assert.strictEqual(func('a'), 5, 'swapping the placeholder preserves previously bound arguments'); _.partial.placeholder = _; }); QUnit.test('bindAll', function(assert) { var curly = {name: 'curly'}; var moe = { name: 'moe', getName: function() { return 'name: ' + this.name; }, sayHi: function() { return 'hi: ' + this.name; } }; curly.getName = moe.getName; var bound = _.bindAll(moe, 'getName', 'sayHi'); assert.strictEqual(bound, moe, 'returns the bound object'); curly.sayHi = moe.sayHi; assert.strictEqual(curly.getName(), 'name: curly', 'unbound function is bound to current object'); assert.strictEqual(curly.sayHi(), 'hi: moe', 'bound function is still bound to original object'); curly = {name: 'curly'}; moe = { name: 'moe', getName: function() { return 'name: ' + this.name; }, sayHi: function() { return 'hi: ' + this.name; }, sayLast: function() { return this.sayHi(_.last(arguments)); } }; assert.raises(function() { _.bindAll(moe); }, Error, 'throws an error for bindAll with no functions named'); assert.raises(function() { _.bindAll(moe, 'sayBye'); }, TypeError, 'throws an error for bindAll if the given key is undefined'); assert.raises(function() { _.bindAll(moe, 'name'); }, TypeError, 'throws an error for bindAll if the given key is not a function'); _.bindAll(moe, 'sayHi', 'sayLast'); curly.sayHi = moe.sayHi; assert.strictEqual(curly.sayHi(), 'hi: moe'); var sayLast = moe.sayLast; assert.strictEqual(sayLast(1, 2, 3, 4, 5, 6, 7, 'Tom'), 'hi: moe', 'createCallback works with any number of arguments'); _.bindAll(moe, ['getName'], [['sayHi']]); var getName = moe.getName; var sayHi = moe.sayHi; assert.strictEqual(getName(), 'name: moe', 'flattens arguments into a single list'); assert.strictEqual(sayHi(), 'hi: moe', 'deeply flattens arguments into a single list'); }); QUnit.test('memoize', function(assert) { var fib = function(n) { return n < 2 ? n : fib(n - 1) + fib(n - 2); }; assert.strictEqual(fib(10), 55, 'a memoized version of fibonacci produces identical results'); fib = _.memoize(fib); // Redefine `fib` for memoization assert.strictEqual(fib(10), 55, 'a memoized version of fibonacci produces identical results'); var o = function(str) { return str; }; var fastO = _.memoize(o); assert.strictEqual(o('toString'), 'toString', 'checks hasOwnProperty'); assert.strictEqual(fastO('toString'), 'toString', 'checks hasOwnProperty'); // Expose the cache. var upper = _.memoize(function(s) { return s.toUpperCase(); }); assert.strictEqual(upper('foo'), 'FOO'); assert.strictEqual(upper('bar'), 'BAR'); assert.deepEqual(upper.cache, {foo: 'FOO', bar: 'BAR'}); upper.cache = {foo: 'BAR', bar: 'FOO'}; assert.strictEqual(upper('foo'), 'BAR'); assert.strictEqual(upper('bar'), 'FOO'); var hashed = _.memoize(function(key) { //https://github.com/jashkenas/underscore/pull/1679#discussion_r13736209 assert.ok(/[a-z]+/.test(key), 'hasher doesn\'t change keys'); return key; }, function(key) { return key.toUpperCase(); }); hashed('yep'); assert.deepEqual(hashed.cache, {YEP: 'yep'}, 'takes a hasher'); // Test that the hash function can be used to swizzle the key. var objCacher = _.memoize(function(value, key) { return {key: key, value: value}; }, function(value, key) { return key; }); var myObj = objCacher('a', 'alpha'); var myObjAlias = objCacher('b', 'alpha'); assert.notStrictEqual(myObj, void 0, 'object is created if second argument used as key'); assert.strictEqual(myObj, myObjAlias, 'object is cached if second argument used as key'); assert.strictEqual(myObj.value, 'a', 'object is not modified if second argument used as key'); }); QUnit.test('delay', function(assert) { assert.expect(2); var done = assert.async(); var delayed = false; _.delay(function(){ delayed = true; }, 100); setTimeout(function(){ assert.ok(!delayed, "didn't delay the function quite yet"); }, 50); setTimeout(function(){ assert.ok(delayed, 'delayed the function'); done(); }, 150); }); QUnit.test('defer', function(assert) { assert.expect(1); var done = assert.async(); var deferred = false; _.defer(function(bool){ deferred = bool; }, true); _.delay(function(){ assert.ok(deferred, 'deferred the function'); done(); }, 50); }); QUnit.test('throttle', function(assert) { assert.expect(2); var done = assert.async(); var counter = 0; var incr = function(){ counter++; }; var throttledIncr = _.throttle(incr, 32); throttledIncr(); throttledIncr(); assert.strictEqual(counter, 1, 'incr was called immediately'); _.delay(function(){ assert.strictEqual(counter, 2, 'incr was throttled'); done(); }, 64); }); QUnit.test('throttle arguments', function(assert) { assert.expect(2); var done = assert.async(); var value = 0; var update = function(val){ value = val; }; var throttledUpdate = _.throttle(update, 32); throttledUpdate(1); throttledUpdate(2); _.delay(function(){ throttledUpdate(3); }, 64); assert.strictEqual(value, 1, 'updated to latest value'); _.delay(function(){ assert.strictEqual(value, 3, 'updated to latest value'); done(); }, 104); }); QUnit.test('throttle once', function(assert) { assert.expect(2); var done = assert.async(); var counter = 0; var incr = function(){ return ++counter; }; var throttledIncr = _.throttle(incr, 32); var result = throttledIncr(); _.delay(function(){ assert.strictEqual(result, 1, 'throttled functions return their value'); assert.strictEqual(counter, 1, 'incr was called once'); done(); }, 64); }); QUnit.test('throttle twice', function(assert) { assert.expect(1); var done = assert.async(); var counter = 0; var incr = function(){ counter++; }; var throttledIncr = _.throttle(incr, 32); throttledIncr(); throttledIncr(); _.delay(function(){ assert.strictEqual(counter, 2, 'incr was called twice'); done(); }, 64); }); QUnit.test('throttle three times', function(assert) { assert.expect(1); var done = assert.async(); var counter = 0; var incr = function(){ counter++; }; var throttledIncr = _.throttle(incr, 32); throttledIncr(); throttledIncr(); throttledIncr(); _.delay(function(){ assert.strictEqual(counter, 2, 'incr was called twice'); done(); }, 64); }); QUnit.test('more throttling', function(assert) { assert.expect(3); var done = assert.async(); var counter = 0; var incr = function(){ counter++; }; var throttledIncr = _.throttle(incr, 30); throttledIncr(); throttledIncr(); assert.strictEqual(counter, 1); _.delay(function(){ assert.strictEqual(counter, 2); throttledIncr(); assert.strictEqual(counter, 3); done(); }, 85); }); QUnit.test('throttle repeatedly with results', function(assert) { assert.expect(6); var done = assert.async(); var counter = 0; var incr = function(){ return ++counter; }; var throttledIncr = _.throttle(incr, 100); var results = []; var saveResult = function() { results.push(throttledIncr()); }; saveResult(); saveResult(); _.delay(saveResult, 50); _.delay(saveResult, 150); _.delay(saveResult, 160); _.delay(saveResult, 230); _.delay(function() { assert.strictEqual(results[0], 1, 'incr was called once'); assert.strictEqual(results[1], 1, 'incr was throttled'); assert.strictEqual(results[2], 1, 'incr was throttled'); assert.strictEqual(results[3], 2, 'incr was called twice'); assert.strictEqual(results[4], 2, 'incr was throttled'); assert.strictEqual(results[5], 3, 'incr was called trailing'); done(); }, 304); }); QUnit.test('throttle triggers trailing call when invoked repeatedly', function(assert) { assert.expect(2); var done = assert.async(); var counter = 0; var limit = 48; var incr = function(){ counter++; }; var throttledIncr = _.throttle(incr, 32); var stamp = new Date; while (new Date - stamp < limit) { throttledIncr(); } var lastCount = counter; assert.ok(counter > 1); _.delay(function() { assert.ok(counter > lastCount); done(); }, 96); }); QUnit.test('throttle does not trigger leading call when leading is set to false', function(assert) { assert.expect(2); var done = assert.async(); var counter = 0; var incr = function(){ counter++; }; var throttledIncr = _.throttle(incr, 60, {leading: false}); throttledIncr(); throttledIncr(); assert.strictEqual(counter, 0); _.delay(function() { assert.strictEqual(counter, 1); done(); }, 96); }); QUnit.test('more throttle does not trigger leading call when leading is set to false', function(assert) { assert.expect(3); var done = assert.async(); var counter = 0; var incr = function(){ counter++; }; var throttledIncr = _.throttle(incr, 100, {leading: false}); throttledIncr(); _.delay(throttledIncr, 50); _.delay(throttledIncr, 60); _.delay(throttledIncr, 200); assert.strictEqual(counter, 0); _.delay(function() { assert.strictEqual(counter, 1); }, 250); _.delay(function() { assert.strictEqual(counter, 2); done(); }, 350); }); QUnit.test('one more throttle with leading: false test', function(assert) { assert.expect(2); var done = assert.async(); var counter = 0; var incr = function(){ counter++; }; var throttledIncr = _.throttle(incr, 100, {leading: false}); var time = new Date; while (new Date - time < 350) throttledIncr(); assert.ok(counter <= 3); _.delay(function() { assert.ok(counter <= 4); done(); }, 200); }); QUnit.test('throttle does not trigger trailing call when trailing is set to false', function(assert) { assert.expect(4); var done = assert.async(); var counter = 0; var incr = function(){ counter++; }; var throttledIncr = _.throttle(incr, 60, {trailing: false}); throttledIncr(); throttledIncr(); throttledIncr(); assert.strictEqual(counter, 1); _.delay(function() { assert.strictEqual(counter, 1); throttledIncr(); throttledIncr(); assert.strictEqual(counter, 2); _.delay(function() { assert.strictEqual(counter, 2); done(); }, 96); }, 96); }); QUnit.test('throttle continues to function after system time is set backwards', function(assert) { assert.expect(2); var done = assert.async(); var counter = 0; var incr = function(){ counter++; }; var throttledIncr = _.throttle(incr, 100); var originalNowFunc = Date.now; var originalGetTimeFunc = Date.prototype.getTime; throttledIncr(); assert.strictEqual(counter, 1, 'incr was called immediately'); Date.prototype.getTime = function() { return +(new Date(2013, 0, 1, 1, 1, 1)); } Date.now = function() { return +(new Date(2013, 0, 1, 1, 1, 1)); } _.delay(function() { throttledIncr(); assert.strictEqual(counter, 2, 'incr was throttled successfully, with tampered system time'); done(); Date.now = originalNowFunc; Date.prototype.getTime = originalGetTimeFunc; }, 200); }); QUnit.test('throttle continues to function after system time is not accessible (or in invalid format)', function(assert) { assert.expect(3); var done = assert.async(); var counter = 0; var incr = function(){ counter++; }; var throttledIncr = _.throttle(incr, 100); var originalNowFunc = Date.now; var originalGetTimeFunc = Date.prototype.getTime; var originalValueOfFunc = Date.prototype.valueOf; throttledIncr(); assert.strictEqual(counter, 1, 'incr was called immediately'); Date.prototype.valueOf = function() { return null; } Date.prototype.getTime = function() { return null; } Date.now = function() { return null; } _.delay(function() { throttledIncr(); assert.strictEqual(counter, 2, 'incr was throttled successfully, with tampered system time'); Date.now = originalNowFunc; Date.prototype.getTime = originalGetTimeFunc; Date.prototype.valueOf = originalValueOfFunc; }, 200); _.delay(function() { throttledIncr(); assert.strictEqual(counter, 3, 'incr was throttled successfully, after system time method restoration'); done(); }, 400); }); QUnit.test('throttle re-entrant', function(assert) { assert.expect(2); var done = assert.async(); var sequence = [ ['b1', 'b2'], ['c1', 'c2'] ]; var value = ''; var throttledAppend; var append = function(arg){ value += this + arg; var args = sequence.pop(); if (args) { throttledAppend.call(args[0], args[1]); } }; throttledAppend = _.throttle(append, 32); throttledAppend.call('a1', 'a2'); assert.strictEqual(value, 'a1a2'); _.delay(function(){ assert.strictEqual(value, 'a1a2c1c2b1b2', 'append was throttled successfully'); done(); }, 104); }); QUnit.test('throttle cancel', function(assert) { var done = assert.async(); var counter = 0; var incr = function(){ counter++; }; var throttledIncr = _.throttle(incr, 32); throttledIncr(); throttledIncr.cancel(); throttledIncr(); throttledIncr(); assert.strictEqual(counter, 2, 'incr was called immediately'); _.delay(function(){ assert.strictEqual(counter, 3, 'incr was throttled'); done(); }, 64); }); QUnit.test('throttle cancel with leading: false', function(assert) { var done = assert.async(); var counter = 0; var incr = function(){ counter++; }; var throttledIncr = _.throttle(incr, 32, {leading: false}); throttledIncr(); throttledIncr.cancel(); assert.strictEqual(counter, 0, 'incr was throttled'); _.delay(function(){ assert.strictEqual(counter, 0, 'incr was throttled'); done(); }, 64); }); QUnit.test('debounce', function(assert) { assert.expect(1); var done = assert.async(); var counter = 0; var incr = function(){ counter++; }; var debouncedIncr = _.debounce(incr, 32); debouncedIncr(); debouncedIncr(); _.delay(debouncedIncr, 16); _.delay(function(){ assert.strictEqual(counter, 1, 'incr was debounced'); done(); }, 96); }); QUnit.test('debounce cancel', function(assert) { assert.expect(1); var done = assert.async(); var counter = 0; var incr = function(){ counter++; }; var debouncedIncr = _.debounce(incr, 32); debouncedIncr(); debouncedIncr.cancel(); _.delay(function(){ assert.strictEqual(counter, 0, 'incr was not called'); done(); }, 96); }); QUnit.test('debounce asap', function(assert) { assert.expect(6); var done = assert.async(); var a, b, c; var counter = 0; var incr = function(){ return ++counter; }; var debouncedIncr = _.debounce(incr, 64, true); a = debouncedIncr(); b = debouncedIncr(); assert.strictEqual(a, 1); assert.strictEqual(b, 1); assert.strictEqual(counter, 1, 'incr was called immediately'); _.delay(debouncedIncr, 16); _.delay(debouncedIncr, 32); _.delay(function() { debouncedIncr(); _.delay(finish, 80); }, 48); var finish = function(){ assert.strictEqual(counter, 1, 'incr was debounced'); c = debouncedIncr(); assert.strictEqual(c, 2); assert.strictEqual(counter, 2, 'incr was called again'); done(); }; }); QUnit.test('debounce asap cancel', function(assert) { assert.expect(4); var done = assert.async(); var a, b; var counter = 0; var incr = function(){ return ++counter; }; var debouncedIncr = _.debounce(incr, 64, true); a = debouncedIncr(); debouncedIncr.cancel(); b = debouncedIncr(); assert.strictEqual(a, 1); assert.strictEqual(b, 2); assert.strictEqual(counter, 2, 'incr was called immediately'); _.delay(debouncedIncr, 16); _.delay(debouncedIncr, 32); _.delay(debouncedIncr, 48); _.delay(function(){ assert.strictEqual(counter, 2, 'incr was debounced'); done(); }, 128); }); QUnit.test('debounce asap recursively', function(assert) { assert.expect(2); var done = assert.async(); var counter = 0; var debouncedIncr = _.debounce(function(){ counter++; if (counter < 10) debouncedIncr(); }, 32, true); debouncedIncr(); assert.strictEqual(counter, 1, 'incr was called immediately'); _.delay(function(){ assert.strictEqual(counter, 1, 'incr was debounced'); done(); }, 96); }); QUnit.test('debounce after system time is set backwards', function(assert) { assert.expect(2); var done = assert.async(); var counter = 0; var debouncedIncr = _.debounce(function(){ counter++; }, 100, true); var originalNowFunc = Date.now; var originalGetTimeFunc = Date.prototype.getTime; debouncedIncr(); assert.strictEqual(counter, 1, 'incr was called immediately'); Date.prototype.getTime = function() { return +(new Date(2013, 0, 1, 1, 1, 1)); } Date.now = function() { return +(new Date(2013, 0, 1, 1, 1, 1)); } _.delay(function() { debouncedIncr(); assert.strictEqual(counter, 2, 'incr was debounced successfully, with tampered system time'); done(); Date.now = originalNowFunc; Date.prototype.getTime = originalGetTimeFunc; }, 200); }); QUnit.test('debounce after system time is is not accessible (or in invalid format)', function(assert) { assert.expect(3); var done = assert.async(); var counter = 0; var debouncedIncr = _.debounce(function(){ counter++; }, 100, true); var originalNowFunc = Date.now; var originalGetTimeFunc = Date.prototype.getTime; var originalValueOfFunc = Date.prototype.valueOf; debouncedIncr(); assert.strictEqual(counter, 1, 'incr was called immediately'); Date.prototype.valueOf = function() { return null; }; Date.prototype.getTime = function() { return null; }; Date.now = function() { return null; }; _.delay(function() { debouncedIncr(); assert.strictEqual(counter, 2, 'incr was debounced successfully, with tampered system time'); Date.now = originalNowFunc; Date.prototype.getTime = originalGetTimeFunc; Date.prototype.valueOf = originalValueOfFunc; }, 200); _.delay(function() { debouncedIncr(); assert.strictEqual(counter, 3, 'incr was debounced successfully, after system time method restoration'); done(); }, 400); }); QUnit.test('debounce re-entrant', function(assert) { assert.expect(2); var done = assert.async(); var sequence = [ ['b1', 'b2'] ]; var value = ''; var debouncedAppend; var append = function(arg){ value += this + arg; var args = sequence.pop(); if (args) { debouncedAppend.call(args[0], args[1]); } }; debouncedAppend = _.debounce(append, 32); debouncedAppend.call('a1', 'a2'); assert.strictEqual(value, ''); _.delay(function(){ assert.strictEqual(value, 'a1a2b1b2', 'append was debounced successfully'); done(); }, 100); }); QUnit.test('once', function(assert) { var num = 0; var increment = _.once(function(){ return ++num; }); increment(); increment(); assert.strictEqual(num, 1); assert.strictEqual(increment(), 1, 'stores a memo to the last value'); }); QUnit.test('Recursive onced function.', function(assert) { assert.expect(1); var f = _.once(function(){ assert.ok(true); f(); }); f(); }); QUnit.test('wrap', function(assert) { var greet = function(name){ return 'hi: ' + name; }; var backwards = _.wrap(greet, function(func, name){ return func(name) + ' ' + name.split('').reverse().join(''); }); assert.strictEqual(backwards('moe'), 'hi: moe eom', 'wrapped the salutation function'); var inner = function(){ return 'Hello '; }; var obj = {name: 'Moe'}; obj.hi = _.wrap(inner, function(fn){ return fn() + this.name; }); assert.strictEqual(obj.hi(), 'Hello Moe'); var noop = function(){}; var wrapped = _.wrap(noop, function(){ return Array.prototype.slice.call(arguments, 0); }); var ret = wrapped(['whats', 'your'], 'vector', 'victor'); assert.deepEqual(ret, [noop, ['whats', 'your'], 'vector', 'victor']); }); QUnit.test('negate', function(assert) { var isOdd = function(n){ return n & 1; }; assert.strictEqual(_.negate(isOdd)(2), true, 'should return the complement of the given function'); assert.strictEqual(_.negate(isOdd)(3), false, 'should return the complement of the given function'); }); QUnit.test('compose', function(assert) { var greet = function(name){ return 'hi: ' + name; }; var exclaim = function(sentence){ return sentence + '!'; }; var composed = _.compose(exclaim, greet); assert.strictEqual(composed('moe'), 'hi: moe!', 'can compose a function that takes another'); composed = _.compose(greet, exclaim); assert.strictEqual(composed('moe'), 'hi: moe!', 'in this case, the functions are also commutative'); // f(g(h(x, y, z))) function h(x, y, z) { assert.strictEqual(arguments.length, 3, 'First function called with multiple args'); return z * y; } function g(x) { assert.strictEqual(arguments.length, 1, 'Composed function is called with 1 argument'); return x; } function f(x) { assert.strictEqual(arguments.length, 1, 'Composed function is called with 1 argument'); return x * 2; } composed = _.compose(f, g, h); assert.strictEqual(composed(1, 2, 3), 12); }); QUnit.test('after', function(assert) { var testAfter = function(afterAmount, timesCalled) { var afterCalled = 0; var after = _.after(afterAmount, function() { afterCalled++; }); while (timesCalled--) after(); return afterCalled; }; assert.strictEqual(testAfter(5, 5), 1, 'after(N) should fire after being called N times'); assert.strictEqual(testAfter(5, 4), 0, 'after(N) should not fire unless called N times'); assert.strictEqual(testAfter(0, 0), 0, 'after(0) should not fire immediately'); assert.strictEqual(testAfter(0, 1), 1, 'after(0) should fire when first invoked'); }); QUnit.test('before', function(assert) { var testBefore = function(beforeAmount, timesCalled) { var beforeCalled = 0; var before = _.before(beforeAmount, function() { beforeCalled++; }); while (timesCalled--) before(); return beforeCalled; }; assert.strictEqual(testBefore(5, 5), 4, 'before(N) should not fire after being called N times'); assert.strictEqual(testBefore(5, 4), 4, 'before(N) should fire before being called N times'); assert.strictEqual(testBefore(0, 0), 0, 'before(0) should not fire immediately'); assert.strictEqual(testBefore(0, 1), 0, 'before(0) should not fire when first invoked'); var context = {num: 0}; var increment = _.before(3, function(){ return ++this.num; }); _.times(10, increment, context); assert.strictEqual(increment(), 2, 'stores a memo to the last value'); assert.strictEqual(context.num, 2, 'provides context'); }); QUnit.test('iteratee', function(assert) { var identity = _.iteratee(); assert.strictEqual(identity, _.identity, '_.iteratee is exposed as an external function.'); function fn() { return arguments; } _.each([_.iteratee(fn), _.iteratee(fn, {})], function(cb) { assert.strictEqual(cb().length, 0); assert.deepEqual(_.toArray(cb(1, 2, 3)), _.range(1, 4)); assert.deepEqual(_.toArray(cb(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)), _.range(1, 11)); }); var deepProperty = _.iteratee(['a', 'b']); assert.strictEqual(deepProperty({a: {b: 2}}), 2, 'treats an array as a deep property accessor'); // Test custom iteratee var builtinIteratee = _.iteratee; _.iteratee = function(value, context) { // RegEx values return a function that returns the number of matches if (_.isRegExp(value)) return function(obj) { return (obj.match(value) || []).length; }; return builtinIteratee(value, context); }; var collection = ['foo', 'bar', 'bbiz']; // Test all methods that claim to be transformed through `_.iteratee` assert.deepEqual(_.countBy(collection, /b/g), {0: 1, 1: 1, 2: 1}); assert.strictEqual(_.every(collection, /b/g), false); assert.deepEqual(_.filter(collection, /b/g), ['bar', 'bbiz']); assert.strictEqual(_.find(collection, /b/g), 'bar'); assert.strictEqual(_.findIndex(collection, /b/g), 1); assert.strictEqual(_.findKey(collection, /b/g), '1'); assert.strictEqual(_.findLastIndex(collection, /b/g), 2); assert.deepEqual(_.groupBy(collection, /b/g), {0: ['foo'], 1: ['bar'], 2: ['bbiz']}); assert.deepEqual(_.indexBy(collection, /b/g), {0: 'foo', 1: 'bar', 2: 'bbiz'}); assert.deepEqual(_.map(collection, /b/g), [0, 1, 2]); assert.strictEqual(_.max(collection, /b/g), 'bbiz'); assert.strictEqual(_.min(collection, /b/g), 'foo'); assert.deepEqual(_.partition(collection, /b/g), [['bar', 'bbiz'], ['foo']]); assert.deepEqual(_.reject(collection, /b/g), ['foo']); assert.strictEqual(_.some(collection, /b/g), true); assert.deepEqual(_.sortBy(collection, /b/g), ['foo', 'bar', 'bbiz']); assert.strictEqual(_.sortedIndex(collection, 'blah', /b/g), 1); assert.deepEqual(_.uniq(collection, /b/g), ['foo', 'bar', 'bbiz']); var objCollection = {a: 'foo', b: 'bar', c: 'bbiz'}; assert.deepEqual(_.mapObject(objCollection, /b/g), {a: 0, b: 1, c: 2}); // Ensure that the overridden iteratee can still fall back on the builtin // iteratee. assert.strictEqual(_.iteratee(), _.identity); assert.deepEqual(_.toArray(_.iteratee(fn)(1, 2, 3)), _.range(1, 4)); var matcher = _.iteratee({b: 'bar'}); assert.equal(matcher(objCollection), true); assert.equal(matcher({}), false); var property = _.iteratee('b'); assert.equal(property(objCollection), 'bar'); assert.equal(property({}), undefined); // Restore the builtin iteratee _.iteratee = builtinIteratee; }); QUnit.test('restArguments', function(assert) { assert.expect(10); _.restArguments(function(a, args) { assert.strictEqual(a, 1); assert.deepEqual(args, [2, 3], 'collects rest arguments into an array'); })(1, 2, 3); _.restArguments(function(a, args) { assert.strictEqual(a, void 0); assert.deepEqual(args, [], 'passes empty array if there are not enough arguments'); })(); _.restArguments(function(a, b, c, args) { assert.strictEqual(arguments.length, 4); assert.deepEqual(args, [4, 5], 'works on functions with many named parameters'); })(1, 2, 3, 4, 5); var obj = {}; _.restArguments(function() { assert.strictEqual(this, obj, 'invokes function with this context'); }).call(obj); _.restArguments(function(array, iteratee, context) { assert.deepEqual(array, [1, 2, 3, 4], 'startIndex can be used manually specify index of rest parameter'); assert.strictEqual(iteratee, void 0); assert.strictEqual(context, void 0); }, 0)(1, 2, 3, 4); }); }()); ================================================ FILE: test/index.html ================================================ Underscore Test Suite
================================================ FILE: test/objects.js ================================================ (function() { var _ = typeof require == 'function' ? require('..') : window._; QUnit.module('Objects'); var testElement = typeof document === 'object' ? document.createElement('div') : void 0; // Some browsers support typed arrays but not DataView and some applications could override DataView var DataViewImpl = typeof NativeDataView !== 'undefined' ? NativeDataView : typeof DataView !== 'undefined' ? DataView : undefined; QUnit.test('keys', function(assert) { assert.deepEqual(_.keys({one: 1, two: 2}), ['one', 'two'], 'can extract the keys from an object'); // the test above is not safe because it relies on for-in enumeration order var a = []; a[1] = 0; assert.deepEqual(_.keys(a), ['1'], 'is not fooled by sparse arrays; see issue #95'); assert.deepEqual(_.keys(null), []); assert.deepEqual(_.keys(void 0), []); assert.deepEqual(_.keys(1), []); assert.deepEqual(_.keys('a'), []); assert.deepEqual(_.keys(true), []); // keys that may be missed if the implementation isn't careful var trouble = { constructor: Object, valueOf: _.noop, hasOwnProperty: null, toString: 5, toLocaleString: void 0, propertyIsEnumerable: /a/, isPrototypeOf: this, __defineGetter__: Boolean, __defineSetter__: {}, __lookupSetter__: false, __lookupGetter__: [] }; var troubleKeys = ['constructor', 'valueOf', 'hasOwnProperty', 'toString', 'toLocaleString', 'propertyIsEnumerable', 'isPrototypeOf', '__defineGetter__', '__defineSetter__', '__lookupSetter__', '__lookupGetter__'].sort(); assert.deepEqual(_.keys(trouble).sort(), troubleKeys, 'matches non-enumerable properties'); }); QUnit.test('allKeys', function(assert) { assert.deepEqual(_.allKeys({one: 1, two: 2}), ['one', 'two'], 'can extract the allKeys from an object'); // the test above is not safe because it relies on for-in enumeration order var a = []; a[1] = 0; assert.deepEqual(_.allKeys(a), ['1'], 'is not fooled by sparse arrays; see issue #95'); a.a = a; assert.deepEqual(_.allKeys(a), ['1', 'a'], 'is not fooled by sparse arrays with additional properties'); _.each([null, void 0, 1, 'a', true, NaN, {}, [], new Number(5), new Date(0)], function(val) { assert.deepEqual(_.allKeys(val), []); }); // allKeys that may be missed if the implementation isn't careful var trouble = { constructor: Object, valueOf: _.noop, hasOwnProperty: null, toString: 5, toLocaleString: void 0, propertyIsEnumerable: /a/, isPrototypeOf: this }; var troubleKeys = ['constructor', 'valueOf', 'hasOwnProperty', 'toString', 'toLocaleString', 'propertyIsEnumerable', 'isPrototypeOf'].sort(); assert.deepEqual(_.allKeys(trouble).sort(), troubleKeys, 'matches non-enumerable properties'); function A() {} A.prototype.foo = 'foo'; var b = new A(); b.bar = 'bar'; assert.deepEqual(_.allKeys(b).sort(), ['bar', 'foo'], 'should include inherited keys'); function y() {} y.x = 'z'; assert.deepEqual(_.allKeys(y), ['x'], 'should get keys from constructor'); }); QUnit.test('values', function(assert) { assert.deepEqual(_.values({one: 1, two: 2}), [1, 2], 'can extract the values from an object'); assert.deepEqual(_.values({one: 1, two: 2, length: 3}), [1, 2, 3], '... even when one of them is "length"'); }); QUnit.test('pairs', function(assert) { assert.deepEqual(_.pairs({one: 1, two: 2}), [['one', 1], ['two', 2]], 'can convert an object into pairs'); assert.deepEqual(_.pairs({one: 1, two: 2, length: 3}), [['one', 1], ['two', 2], ['length', 3]], '... even when one of them is "length"'); }); QUnit.test('invert', function(assert) { var obj = {first: 'Moe', second: 'Larry', third: 'Curly'}; assert.deepEqual(_.keys(_.invert(obj)), ['Moe', 'Larry', 'Curly'], 'can invert an object'); assert.deepEqual(_.invert(_.invert(obj)), obj, 'two inverts gets you back where you started'); obj = {length: 3}; assert.strictEqual(_.invert(obj)['3'], 'length', 'can invert an object with "length"'); }); QUnit.test('functions', function(assert) { var obj = {a: 'dash', b: _.map, c: /yo/, d: _.reduce}; assert.deepEqual(['b', 'd'], _.functions(obj), 'can grab the function names of any passed-in object'); var Animal = function(){}; Animal.prototype.run = function(){}; assert.deepEqual(_.functions(new Animal), ['run'], 'also looks up functions on the prototype'); }); QUnit.test('methods', function(assert) { assert.strictEqual(_.methods, _.functions, 'is an alias for functions'); }); QUnit.test('extend', function(assert) { var result; assert.strictEqual(_.extend({}, {a: 'b'}).a, 'b', 'can extend an object with the attributes of another'); assert.strictEqual(_.extend({a: 'x'}, {a: 'b'}).a, 'b', 'properties in source override destination'); assert.strictEqual(_.extend({x: 'x'}, {a: 'b'}).x, 'x', "properties not in source don't get overridden"); result = _.extend({x: 'x'}, {a: 'a'}, {b: 'b'}); assert.deepEqual(result, {x: 'x', a: 'a', b: 'b'}, 'can extend from multiple source objects'); result = _.extend({x: 'x'}, {a: 'a', x: 2}, {a: 'b'}); assert.deepEqual(result, {x: 2, a: 'b'}, 'extending from multiple source objects last property trumps'); result = _.extend({}, {a: void 0, b: null}); assert.deepEqual(_.keys(result), ['a', 'b'], 'extend copies undefined values'); var F = function() {}; F.prototype = {a: 'b'}; var subObj = new F(); subObj.c = 'd'; assert.deepEqual(_.extend({}, subObj), {a: 'b', c: 'd'}, 'extend copies all properties from source'); _.extend(subObj, {}); assert.ok(!subObj.hasOwnProperty('a'), "extend does not convert destination object's 'in' properties to 'own' properties"); try { result = {}; _.extend(result, null, void 0, {a: 1}); } catch (e) { /* ignored */ } assert.strictEqual(result.a, 1, 'should not error on `null` or `undefined` sources'); assert.strictEqual(_.extend(null, {a: 1}), null, 'extending null results in null'); assert.strictEqual(_.extend(void 0, {a: 1}), void 0, 'extending undefined results in undefined'); }); QUnit.test('extendOwn', function(assert) { var result; assert.strictEqual(_.extendOwn({}, {a: 'b'}).a, 'b', 'can extend an object with the attributes of another'); assert.strictEqual(_.extendOwn({a: 'x'}, {a: 'b'}).a, 'b', 'properties in source override destination'); assert.strictEqual(_.extendOwn({x: 'x'}, {a: 'b'}).x, 'x', "properties not in source don't get overridden"); result = _.extendOwn({x: 'x'}, {a: 'a'}, {b: 'b'}); assert.deepEqual(result, {x: 'x', a: 'a', b: 'b'}, 'can extend from multiple source objects'); result = _.extendOwn({x: 'x'}, {a: 'a', x: 2}, {a: 'b'}); assert.deepEqual(result, {x: 2, a: 'b'}, 'extending from multiple source objects last property trumps'); assert.deepEqual(_.extendOwn({}, {a: void 0, b: null}), {a: void 0, b: null}, 'copies undefined values'); var F = function() {}; F.prototype = {a: 'b'}; var subObj = new F(); subObj.c = 'd'; assert.deepEqual(_.extendOwn({}, subObj), {c: 'd'}, 'copies own properties from source'); result = {}; assert.deepEqual(_.extendOwn(result, null, void 0, {a: 1}), {a: 1}, 'should not error on `null` or `undefined` sources'); _.each(['a', 5, null, false], function(val) { assert.strictEqual(_.extendOwn(val, {a: 1}), val, 'extending non-objects results in returning the non-object value'); }); assert.strictEqual(_.extendOwn(void 0, {a: 1}), void 0, 'extending undefined results in undefined'); result = _.extendOwn({a: 1, 0: 2, 1: '5', length: 6}, {0: 1, 1: 2, length: 2}); assert.deepEqual(result, {a: 1, 0: 1, 1: 2, length: 2}, 'should treat array-like objects like normal objects'); }); QUnit.test('assign', function(assert) { assert.strictEqual(_.assign, _.extendOwn, 'is an alias for extendOwn'); }); QUnit.test('pick', function(assert) { var result; result = _.pick({a: 1, b: 2, c: 3}, 'a', 'c'); assert.deepEqual(result, {a: 1, c: 3}, 'can restrict properties to those named'); result = _.pick({a: 1, b: 2, c: 3}, ['b', 'c']); assert.deepEqual(result, {b: 2, c: 3}, 'can restrict properties to those named in an array'); result = _.pick({a: 1, b: 2, c: 3}, ['a'], 'b'); assert.deepEqual(result, {a: 1, b: 2}, 'can restrict properties to those named in mixed args'); result = _.pick({a: 1, b: 2, c: 3}, ['a'], [['b']]); assert.deepEqual(result, {a: 1, b: 2}, 'can restrict properties to those named in mixed deep args'); result = _.pick(['a', 'b'], 1); assert.deepEqual(result, {1: 'b'}, 'can pick numeric properties'); _.each([null, void 0], function(val) { assert.deepEqual(_.pick(val, 'hasOwnProperty'), {}, 'Called with null/undefined'); assert.deepEqual(_.pick(val, _.constant(true)), {}); }); assert.deepEqual(_.pick(5, 'toString', 'b'), {toString: Number.prototype.toString}, 'can iterate primitives'); var data = {a: 1, b: 2, c: 3}; var callback = function(value, key, object) { assert.strictEqual(key, {1: 'a', 2: 'b', 3: 'c'}[value]); assert.strictEqual(object, data); return value !== this.value; }; result = _.pick(data, callback, {value: 2}); assert.deepEqual(result, {a: 1, c: 3}, 'can accept a predicate and context'); var Obj = function(){}; Obj.prototype = {a: 1, b: 2, c: 3}; var instance = new Obj(); assert.deepEqual(_.pick(instance, 'a', 'c'), {a: 1, c: 3}, 'include prototype props'); assert.deepEqual(_.pick(data, function(val, key) { return this[key] === 3 && this === instance; }, instance), {c: 3}, 'function is given context'); assert.ok(!_.has(_.pick({}, 'foo'), 'foo'), 'does not set own property if property not in object'); _.pick(data, function(value, key, obj) { assert.strictEqual(obj, data, 'passes same object as third parameter of iteratee'); }); }); QUnit.test('omit', function(assert) { var result; result = _.omit({a: 1, b: 2, c: 3}, 'b'); assert.deepEqual(result, {a: 1, c: 3}, 'can omit a single named property'); result = _.omit({a: 1, b: 2, c: 3}, 'a', 'c'); assert.deepEqual(result, {b: 2}, 'can omit several named properties'); result = _.omit({a: 1, b: 2, c: 3}, ['b', 'c']); assert.deepEqual(result, {a: 1}, 'can omit properties named in an array'); result = _.omit({a: 1, b: 2, c: 3}, ['b', ['c']]); assert.deepEqual(result, {a: 1}, 'can omit properties named in a nested array'); result = _.omit(['a', 'b'], 0); assert.deepEqual(result, {1: 'b'}, 'can omit numeric properties'); assert.deepEqual(_.omit(null, 'a', 'b'), {}, 'non objects return empty object'); assert.deepEqual(_.omit(void 0, 'toString'), {}, 'null/undefined return empty object'); assert.deepEqual(_.omit(5, 'toString', 'b'), {}, 'returns empty object for primitives'); var data = {a: 1, b: 2, c: 3}; var callback = function(value, key, object) { assert.strictEqual(key, {1: 'a', 2: 'b', 3: 'c'}[value]); assert.strictEqual(object, data); return value !== this.value; }; result = _.omit(data, callback, {value: 2}); assert.deepEqual(result, {b: 2}, 'can accept a predicate'); var Obj = function(){}; Obj.prototype = {a: 1, b: 2, c: 3}; var instance = new Obj(); assert.deepEqual(_.omit(instance, 'b'), {a: 1, c: 3}, 'include prototype props'); assert.deepEqual(_.omit(data, function(val, key) { return this[key] === 3 && this === instance; }, instance), {a: 1, b: 2}, 'function is given context'); }); QUnit.test('defaults', function(assert) { var options = {zero: 0, one: 1, empty: '', nan: NaN, nothing: null}; _.defaults(options, {zero: 1, one: 10, twenty: 20, nothing: 'str'}); assert.strictEqual(options.zero, 0, 'value exists'); assert.strictEqual(options.one, 1, 'value exists'); assert.strictEqual(options.twenty, 20, 'default applied'); assert.strictEqual(options.nothing, null, "null isn't overridden"); _.defaults(options, {empty: 'full'}, {nan: 'nan'}, {word: 'word'}, {word: 'dog'}); assert.strictEqual(options.empty, '', 'value exists'); assert.ok(_.isNaN(options.nan), "NaN isn't overridden"); assert.strictEqual(options.word, 'word', 'new value is added, first one wins'); try { options = {}; _.defaults(options, null, void 0, {a: 1}); } catch (e) { /* ignored */ } assert.strictEqual(options.a, 1, 'should not error on `null` or `undefined` sources'); assert.deepEqual(_.defaults(null, {a: 1}), {a: 1}, 'defaults skips nulls'); assert.deepEqual(_.defaults(void 0, {a: 1}), {a: 1}, 'defaults skips undefined'); }); QUnit.test('clone', function(assert) { var moe = {name: 'moe', lucky: [13, 27, 34]}; var clone = _.clone(moe); assert.strictEqual(clone.name, 'moe', 'the clone as the attributes of the original'); clone.name = 'curly'; assert.ok(clone.name === 'curly' && moe.name === 'moe', 'clones can change shallow attributes without affecting the original'); clone.lucky.push(101); assert.strictEqual(_.last(moe.lucky), 101, 'changes to deep attributes are shared with the original'); assert.strictEqual(_.clone(void 0), void 0, 'non objects should not be changed by clone'); assert.strictEqual(_.clone(1), 1, 'non objects should not be changed by clone'); assert.strictEqual(_.clone(null), null, 'non objects should not be changed by clone'); }); QUnit.test('create', function(assert) { var Parent = function() {}; Parent.prototype = {foo: function() {}, bar: 2}; _.each(['foo', null, void 0, 1], function(val) { assert.deepEqual(_.create(val), {}, 'should return empty object when a non-object is provided'); }); assert.ok(_.create([]) instanceof Array, 'should return new instance of array when array is provided'); var Child = function() {}; Child.prototype = _.create(Parent.prototype); assert.ok(new Child instanceof Parent, 'object should inherit prototype'); var func = function() {}; Child.prototype = _.create(Parent.prototype, {func: func}); assert.strictEqual(Child.prototype.func, func, 'properties should be added to object'); Child.prototype = _.create(Parent.prototype, {constructor: Child}); assert.strictEqual(Child.prototype.constructor, Child); Child.prototype.foo = 'foo'; var created = _.create(Child.prototype, new Child); assert.ok(!created.hasOwnProperty('foo'), 'should only add own properties'); }); QUnit.test('isEqual', function(assert) { function First() { this.value = 1; } First.prototype.value = 1; function Second() { this.value = 1; } Second.prototype.value = 2; // Basic equality and identity comparisons. assert.ok(_.isEqual(null, null), '`null` is equal to `null`'); assert.ok(_.isEqual(), '`undefined` is equal to `undefined`'); assert.ok(!_.isEqual(0, -0), '`0` is not equal to `-0`'); assert.ok(!_.isEqual(-0, 0), 'Commutative equality is implemented for `0` and `-0`'); assert.ok(!_.isEqual(null, void 0), '`null` is not equal to `undefined`'); assert.ok(!_.isEqual(void 0, null), 'Commutative equality is implemented for `null` and `undefined`'); // String object and primitive comparisons. assert.ok(_.isEqual('Curly', 'Curly'), 'Identical string primitives are equal'); assert.ok(_.isEqual(new String('Curly'), new String('Curly')), 'String objects with identical primitive values are equal'); assert.ok(_.isEqual(new String('Curly'), 'Curly'), 'String primitives and their corresponding object wrappers are equal'); assert.ok(_.isEqual('Curly', new String('Curly')), 'Commutative equality is implemented for string objects and primitives'); assert.ok(!_.isEqual('Curly', 'Larry'), 'String primitives with different values are not equal'); assert.ok(!_.isEqual(new String('Curly'), new String('Larry')), 'String objects with different primitive values are not equal'); assert.ok(!_.isEqual(new String('Curly'), {toString: function(){ return 'Curly'; }}), 'String objects and objects with a custom `toString` method are not equal'); // Number object and primitive comparisons. assert.ok(_.isEqual(75, 75), 'Identical number primitives are equal'); assert.ok(_.isEqual(new Number(75), new Number(75)), 'Number objects with identical primitive values are equal'); assert.ok(_.isEqual(75, new Number(75)), 'Number primitives and their corresponding object wrappers are equal'); assert.ok(_.isEqual(new Number(75), 75), 'Commutative equality is implemented for number objects and primitives'); assert.ok(!_.isEqual(new Number(0), -0), '`new Number(0)` and `-0` are not equal'); assert.ok(!_.isEqual(0, new Number(-0)), 'Commutative equality is implemented for `new Number(0)` and `-0`'); assert.ok(!_.isEqual(new Number(75), new Number(63)), 'Number objects with different primitive values are not equal'); assert.ok(!_.isEqual(new Number(63), {valueOf: function(){ return 63; }}), 'Number objects and objects with a `valueOf` method are not equal'); // Comparisons involving `NaN`. assert.ok(_.isEqual(NaN, NaN), '`NaN` is equal to `NaN`'); assert.ok(_.isEqual(new Number(NaN), NaN), 'Object(`NaN`) is equal to `NaN`'); assert.ok(!_.isEqual(61, NaN), 'A number primitive is not equal to `NaN`'); assert.ok(!_.isEqual(new Number(79), NaN), 'A number object is not equal to `NaN`'); assert.ok(!_.isEqual(Infinity, NaN), '`Infinity` is not equal to `NaN`'); // Boolean object and primitive comparisons. assert.ok(_.isEqual(true, true), 'Identical boolean primitives are equal'); assert.ok(_.isEqual(new Boolean, new Boolean), 'Boolean objects with identical primitive values are equal'); assert.ok(_.isEqual(true, new Boolean(true)), 'Boolean primitives and their corresponding object wrappers are equal'); assert.ok(_.isEqual(new Boolean(true), true), 'Commutative equality is implemented for booleans'); assert.ok(!_.isEqual(new Boolean(true), new Boolean), 'Boolean objects with different primitive values are not equal'); // Common type coercions. assert.ok(!_.isEqual(new Boolean(false), true), '`new Boolean(false)` is not equal to `true`'); assert.ok(!_.isEqual('75', 75), 'String and number primitives with like values are not equal'); assert.ok(!_.isEqual(new Number(63), new String(63)), 'String and number objects with like values are not equal'); assert.ok(!_.isEqual(75, '75'), 'Commutative equality is implemented for like string and number values'); assert.ok(!_.isEqual(0, ''), 'Number and string primitives with like values are not equal'); assert.ok(!_.isEqual(1, true), 'Number and boolean primitives with like values are not equal'); assert.ok(!_.isEqual(new Boolean(false), new Number(0)), 'Boolean and number objects with like values are not equal'); assert.ok(!_.isEqual(false, new String('')), 'Boolean primitives and string objects with like values are not equal'); assert.ok(!_.isEqual(12564504e5, new Date(2009, 9, 25)), 'Dates and their corresponding numeric primitive values are not equal'); // Dates. assert.ok(_.isEqual(new Date(2009, 9, 25), new Date(2009, 9, 25)), 'Date objects referencing identical times are equal'); assert.ok(!_.isEqual(new Date(2009, 9, 25), new Date(2009, 11, 13)), 'Date objects referencing different times are not equal'); assert.ok(!_.isEqual(new Date(2009, 11, 13), { getTime: function(){ return 12606876e5; } }), 'Date objects and objects with a `getTime` method are not equal'); assert.ok(!_.isEqual(new Date('Curly'), new Date('Curly')), 'Invalid dates are not equal'); // Functions. assert.ok(!_.isEqual(First, Second), 'Different functions with identical bodies and source code representations are not equal'); // RegExps. assert.ok(_.isEqual(/(?:)/gim, /(?:)/gim), 'RegExps with equivalent patterns and flags are equal'); assert.ok(_.isEqual(/(?:)/gi, /(?:)/ig), 'Flag order is not significant'); assert.ok(!_.isEqual(/(?:)/g, /(?:)/gi), 'RegExps with equivalent patterns and different flags are not equal'); assert.ok(!_.isEqual(/Moe/gim, /Curly/gim), 'RegExps with different patterns and equivalent flags are not equal'); assert.ok(!_.isEqual(/(?:)/gi, /(?:)/g), 'Commutative equality is implemented for RegExps'); assert.ok(!_.isEqual(/Curly/g, {source: 'Larry', global: true, ignoreCase: false, multiline: false}), 'RegExps and RegExp-like objects are not equal'); // Empty arrays, array-like objects, and object literals. assert.ok(_.isEqual({}, {}), 'Empty object literals are equal'); assert.ok(_.isEqual([], []), 'Empty array literals are equal'); assert.ok(_.isEqual([{}], [{}]), 'Empty nested arrays and objects are equal'); assert.ok(!_.isEqual({length: 0}, []), 'Array-like objects and arrays are not equal.'); assert.ok(!_.isEqual([], {length: 0}), 'Commutative equality is implemented for array-like objects'); assert.ok(!_.isEqual({}, []), 'Object literals and array literals are not equal'); assert.ok(!_.isEqual([], {}), 'Commutative equality is implemented for objects and arrays'); // Arrays with primitive and object values. assert.ok(_.isEqual([1, 'Larry', true], [1, 'Larry', true]), 'Arrays containing identical primitives are equal'); assert.ok(_.isEqual([/Moe/g, new Date(2009, 9, 25)], [/Moe/g, new Date(2009, 9, 25)]), 'Arrays containing equivalent elements are equal'); // Multi-dimensional arrays. var a = [new Number(47), false, 'Larry', /Moe/, new Date(2009, 11, 13), ['running', 'biking', new String('programming')], {a: 47}]; var b = [new Number(47), false, 'Larry', /Moe/, new Date(2009, 11, 13), ['running', 'biking', new String('programming')], {a: 47}]; assert.ok(_.isEqual(a, b), 'Arrays containing nested arrays and objects are recursively compared'); // Overwrite the methods defined in ES 5.1 section 15.4.4. a.forEach = a.map = a.filter = a.every = a.indexOf = a.lastIndexOf = a.some = a.reduce = a.reduceRight = null; b.join = b.pop = b.reverse = b.shift = b.slice = b.splice = b.concat = b.sort = b.unshift = null; // Array elements and properties. assert.ok(_.isEqual(a, b), 'Arrays containing equivalent elements and different non-numeric properties are equal'); a.push('White Rocks'); assert.ok(!_.isEqual(a, b), 'Arrays of different lengths are not equal'); a.push('East Boulder'); b.push('Gunbarrel Ranch', 'Teller Farm'); assert.ok(!_.isEqual(a, b), 'Arrays of identical lengths containing different elements are not equal'); // Sparse arrays. assert.ok(_.isEqual(Array(3), Array(3)), 'Sparse arrays of identical lengths are equal'); assert.ok(!_.isEqual(Array(3), Array(6)), 'Sparse arrays of different lengths are not equal when both are empty'); var sparse = []; sparse[1] = 5; assert.ok(_.isEqual(sparse, [void 0, 5]), 'Handles sparse arrays as dense'); // Simple objects. assert.ok(_.isEqual({a: 'Curly', b: 1, c: true}, {a: 'Curly', b: 1, c: true}), 'Objects containing identical primitives are equal'); assert.ok(_.isEqual({a: /Curly/g, b: new Date(2009, 11, 13)}, {a: /Curly/g, b: new Date(2009, 11, 13)}), 'Objects containing equivalent members are equal'); assert.ok(!_.isEqual({a: 63, b: 75}, {a: 61, b: 55}), 'Objects of identical sizes with different values are not equal'); assert.ok(!_.isEqual({a: 63, b: 75}, {a: 61, c: 55}), 'Objects of identical sizes with different property names are not equal'); assert.ok(!_.isEqual({a: 1, b: 2}, {a: 1}), 'Objects of different sizes are not equal'); assert.ok(!_.isEqual({a: 1}, {a: 1, b: 2}), 'Commutative equality is implemented for objects'); assert.ok(!_.isEqual({x: 1, y: void 0}, {x: 1, z: 2}), 'Objects with identical keys and different values are not equivalent'); // Extremely deeply nested objects (CVE-2026-27601). a = b = 'v'; for (var i = 0; i < 30000; ++i) { a = {x: a}; b = {x: b}; } assert.ok(_.isEqual(a, b), 'Very deeply nested objects can be equal'); b = {x: b}; assert.ok(!_.isEqual(a, b), 'Very deeply nested objects can be different'); assert.ok(!_.isEqual(b, a), 'Commutative equality is implemented for very deeply nested objects'); // `A` contains nested objects and arrays. a = { name: new String('Moe Howard'), age: new Number(77), stooge: true, hobbies: ['acting'], film: { name: 'Sing a Song of Six Pants', release: new Date(1947, 9, 30), stars: [new String('Larry Fine'), 'Shemp Howard'], minutes: new Number(16), seconds: 54 } }; // `B` contains equivalent nested objects and arrays. b = { name: new String('Moe Howard'), age: new Number(77), stooge: true, hobbies: ['acting'], film: { name: 'Sing a Song of Six Pants', release: new Date(1947, 9, 30), stars: [new String('Larry Fine'), 'Shemp Howard'], minutes: new Number(16), seconds: 54 } }; assert.ok(_.isEqual(a, b), 'Objects with nested equivalent members are recursively compared'); // Instances. assert.ok(_.isEqual(new First, new First), 'Object instances are equal'); assert.ok(!_.isEqual(new First, new Second), 'Objects with different constructors and identical own properties are not equal'); assert.ok(!_.isEqual({value: 1}, new First), 'Object instances and objects sharing equivalent properties are not equal'); assert.ok(!_.isEqual({value: 2}, new Second), 'The prototype chain of objects should not be examined'); // Circular Arrays. (a = []).push(a); (b = []).push(b); assert.ok(_.isEqual(a, b), 'Arrays containing circular references are equal'); a.push(new String('Larry')); b.push(new String('Larry')); assert.ok(_.isEqual(a, b), 'Arrays containing circular references and equivalent properties are equal'); a.push('Shemp'); b.push('Curly'); assert.ok(!_.isEqual(a, b), 'Arrays containing circular references and different properties are not equal'); // More circular arrays #767. a = ['everything is checked but', 'this', 'is not']; a[1] = a; b = ['everything is checked but', ['this', 'array'], 'is not']; assert.ok(!_.isEqual(a, b), 'Comparison of circular references with non-circular references are not equal'); // Circular Objects. a = {abc: null}; b = {abc: null}; a.abc = a; b.abc = b; assert.ok(_.isEqual(a, b), 'Objects containing circular references are equal'); a.def = 75; b.def = 75; assert.ok(_.isEqual(a, b), 'Objects containing circular references and equivalent properties are equal'); a.def = new Number(75); b.def = new Number(63); assert.ok(!_.isEqual(a, b), 'Objects containing circular references and different properties are not equal'); // More circular objects #767. a = {everything: 'is checked', but: 'this', is: 'not'}; a.but = a; b = {everything: 'is checked', but: {that: 'object'}, is: 'not'}; assert.ok(!_.isEqual(a, b), 'Comparison of circular references with non-circular object references are not equal'); // Cyclic Structures. a = [{abc: null}]; b = [{abc: null}]; (a[0].abc = a).push(a); (b[0].abc = b).push(b); assert.ok(_.isEqual(a, b), 'Cyclic structures are equal'); a[0].def = 'Larry'; b[0].def = 'Larry'; assert.ok(_.isEqual(a, b), 'Cyclic structures containing equivalent properties are equal'); a[0].def = new String('Larry'); b[0].def = new String('Curly'); assert.ok(!_.isEqual(a, b), 'Cyclic structures containing different properties are not equal'); // Complex Circular References. a = {foo: {b: {foo: {c: {foo: null}}}}}; b = {foo: {b: {foo: {c: {foo: null}}}}}; a.foo.b.foo.c.foo = a; b.foo.b.foo.c.foo = b; assert.ok(_.isEqual(a, b), 'Cyclic structures with nested and identically-named properties are equal'); // Chaining. assert.ok(!_.isEqual(_({x: 1, y: void 0}).chain(), _({x: 1, z: 2}).chain()), 'Chained objects containing different values are not equal'); a = _({x: 1, y: 2}).chain(); b = _({x: 1, y: 2}).chain(); assert.strictEqual(_.isEqual(a.isEqual(b), _(true)), true, '`isEqual` can be chained'); // Objects without a `constructor` property if (Object.create) { a = Object.create(null, {x: {value: 1, enumerable: true}}); b = {x: 1}; assert.ok(_.isEqual(a, b), 'Handles objects without a constructor (e.g. from Object.create'); } function Foo() { this.a = 1; } Foo.prototype.constructor = null; var other = {a: 1}; assert.strictEqual(_.isEqual(new Foo, other), false, 'Objects from different constructors are not equal'); // Tricky object cases val comparisons assert.strictEqual(_.isEqual([0], [-0]), false); assert.strictEqual(_.isEqual({a: 0}, {a: -0}), false); assert.strictEqual(_.isEqual([NaN], [NaN]), true); assert.strictEqual(_.isEqual({a: NaN}, {a: NaN}), true); if (typeof Symbol !== 'undefined') { var symbol = Symbol('x'); assert.strictEqual(_.isEqual(symbol, symbol), true, 'A symbol is equal to itself'); assert.strictEqual(_.isEqual(symbol, Object(symbol)), true, 'Even when wrapped in Object()'); assert.strictEqual(_.isEqual(symbol, null), false, 'Different types are not equal'); var symbolY = Symbol('y'); assert.strictEqual(_.isEqual(symbol, symbolY), false, 'Different symbols are not equal'); var sameStringSymbol = Symbol('x'); assert.strictEqual(_.isEqual(symbol, sameStringSymbol), false, 'Different symbols of same string are not equal'); } // typed arrays if (typeof ArrayBuffer !== 'undefined') { var u8 = new Uint8Array([1, 2]); var u8b = new Uint8Array([1, 2]); var i8 = new Int8Array([1, 2]); var u16 = new Uint16Array([1, 2]); var u16one = new Uint16Array([3]); assert.ok(_.isEqual(u8, u8b), 'Identical typed array data are equal'); assert.ok(_.isEqual(u8.buffer, u8b.buffer), 'Identical ArrayBuffers are equal'); assert.ok(_.isEqual(u8.buffer, i8.buffer), 'Identical ArrayBuffers of different typed arrays are equal'); assert.notOk(_.isEqual({a: 1, buffer: u8.buffer}, {a: 2, buffer: u8b.buffer}), 'Unequal objects with similar buffer properties are not equals'); assert.notOk(_.isEqual(u8, i8), 'Different types of typed arrays with the same byte data are not equal'); assert.notOk(_.isEqual(u8, u16), 'Typed arrays with different types and different byte length are not equal'); assert.notOk(_.isEqual(u8, u16one), 'Typed arrays with different types, same byte length but different byte data are not equal'); assert.notOk(_.isEqual(u8.buffer, u16.buffer), 'Different ArrayBuffers with different length are not equal'); assert.notOk(_.isEqual(u8.buffer, u16one.buffer), 'Different ArrayBuffers with different byte data are not equal'); // Regression tests for #2875. var shared = new Uint8Array([1, 2, 3, 4]); var view1 = new Uint8Array(shared.buffer, 0, 2); var view2 = new Uint8Array(shared.buffer, 2, 2); assert.notOk(_.isEqual(view1, view2), 'same buffer with different offset is not equal'); // Some older browsers support typed arrays but not DataView. if (DataViewImpl) { assert.ok(_.isEqual(new DataViewImpl(u8.buffer), new DataViewImpl(u8b.buffer)), 'Identical DataViews are equal'); assert.ok(_.isEqual(new DataViewImpl(u8.buffer), new DataViewImpl(i8.buffer)), 'Identical DataViews of different typed arrays are equal'); assert.notOk(_.isEqual(new DataViewImpl(u8.buffer), new DataViewImpl(u16.buffer)), 'Different DataViews with different length are not equal'); assert.notOk(_.isEqual(new DataViewImpl(u8.buffer), new DataViewImpl(u16one.buffer)), 'Different DataViews with different byte data are not equal'); } } }); QUnit.test('isEmpty', function(assert) { assert.ok(!_([1]).isEmpty(), '[1] is not empty'); assert.ok(_.isEmpty([]), '[] is empty'); assert.ok(!_.isEmpty({one: 1}), '{one: 1} is not empty'); assert.ok(_.isEmpty({}), '{} is empty'); assert.ok(_.isEmpty(new RegExp('')), 'objects with prototype properties are empty'); assert.ok(_.isEmpty(null), 'null is empty'); assert.ok(_.isEmpty(), 'undefined is empty'); assert.ok(_.isEmpty(''), 'the empty string is empty'); assert.ok(!_.isEmpty('moe'), 'but other strings are not'); var obj = {one: 1}; delete obj.one; assert.ok(_.isEmpty(obj), 'deleting all the keys from an object empties it'); var args = function(){ return arguments; }; assert.ok(_.isEmpty(args()), 'empty arguments object is empty'); assert.ok(!_.isEmpty(args('')), 'non-empty arguments object is not empty'); // covers collecting non-enumerable properties in IE < 9 var nonEnumProp = {toString: 5}; assert.ok(!_.isEmpty(nonEnumProp), 'non-enumerable property is not empty'); }); if (typeof document === 'object') { QUnit.test('isElement', function(assert) { assert.ok(!_.isElement('div'), 'strings are not dom elements'); assert.ok(_.isElement(testElement), 'an element is a DOM element'); }); } QUnit.test('isArguments', function(assert) { var args = (function(){ return arguments; }(1, 2, 3)); assert.ok(!_.isArguments('string'), 'a string is not an arguments object'); assert.ok(!_.isArguments(_.isArguments), 'a function is not an arguments object'); assert.ok(_.isArguments(args), 'but the arguments object is an arguments object'); assert.ok(!_.isArguments(_.toArray(args)), 'but not when it\'s converted into an array'); assert.ok(!_.isArguments([1, 2, 3]), 'and not vanilla arrays.'); }); QUnit.test('isObject', function(assert) { assert.ok(_.isObject(arguments), 'the arguments object is object'); assert.ok(_.isObject([1, 2, 3]), 'and arrays'); if (testElement) { assert.ok(_.isObject(testElement), 'and DOM element'); } assert.ok(_.isObject(function() {}), 'and functions'); assert.ok(!_.isObject(null), 'but not null'); assert.ok(!_.isObject(void 0), 'and not undefined'); assert.ok(!_.isObject('string'), 'and not string'); assert.ok(!_.isObject(12), 'and not number'); assert.ok(!_.isObject(true), 'and not boolean'); assert.ok(_.isObject(new String('string')), 'but new String()'); }); QUnit.test('isArray', function(assert) { assert.ok(!_.isArray(void 0), 'undefined vars are not arrays'); assert.ok(!_.isArray(arguments), 'the arguments object is not an array'); assert.ok(_.isArray([1, 2, 3]), 'but arrays are'); }); QUnit.test('isString', function(assert) { var obj = new String('I am a string object'); if (testElement) { assert.ok(!_.isString(testElement), 'an element is not a string'); } assert.ok(_.isString([1, 2, 3].join(', ')), 'but strings are'); assert.strictEqual(_.isString('I am a string literal'), true, 'string literals are'); assert.ok(_.isString(obj), 'so are String objects'); assert.strictEqual(_.isString(1), false); }); QUnit.test('isSymbol', function(assert) { assert.ok(!_.isSymbol(0), 'numbers are not symbols'); assert.ok(!_.isSymbol(''), 'strings are not symbols'); assert.ok(!_.isSymbol(_.isSymbol), 'functions are not symbols'); if (typeof Symbol === 'function') { assert.ok(_.isSymbol(Symbol()), 'symbols are symbols'); assert.ok(_.isSymbol(Symbol('description')), 'described symbols are symbols'); assert.ok(_.isSymbol(Object(Symbol())), 'boxed symbols are symbols'); } }); QUnit.test('isNumber', function(assert) { assert.ok(!_.isNumber('string'), 'a string is not a number'); assert.ok(!_.isNumber(arguments), 'the arguments object is not a number'); assert.ok(!_.isNumber(void 0), 'undefined is not a number'); assert.ok(_.isNumber(3 * 4 - 7 / 10), 'but numbers are'); assert.ok(_.isNumber(NaN), 'NaN *is* a number'); assert.ok(_.isNumber(Infinity), 'Infinity is a number'); assert.ok(!_.isNumber('1'), 'numeric strings are not numbers'); }); QUnit.test('isBoolean', function(assert) { assert.ok(!_.isBoolean(2), 'a number is not a boolean'); assert.ok(!_.isBoolean('string'), 'a string is not a boolean'); assert.ok(!_.isBoolean('false'), 'the string "false" is not a boolean'); assert.ok(!_.isBoolean('true'), 'the string "true" is not a boolean'); assert.ok(!_.isBoolean(arguments), 'the arguments object is not a boolean'); assert.ok(!_.isBoolean(void 0), 'undefined is not a boolean'); assert.ok(!_.isBoolean(NaN), 'NaN is not a boolean'); assert.ok(!_.isBoolean(null), 'null is not a boolean'); assert.ok(_.isBoolean(true), 'but true is'); assert.ok(_.isBoolean(false), 'and so is false'); }); QUnit.test('isMap', function(assert) { assert.ok(!_.isMap('string'), 'a string is not a map'); assert.ok(!_.isMap(2), 'a number is not a map'); assert.ok(!_.isMap({}), 'an object is not a map'); assert.ok(!_.isMap(false), 'a boolean is not a map'); assert.ok(!_.isMap(void 0), 'undefined is not a map'); assert.ok(!_.isMap([1, 2, 3]), 'an array is not a map'); if (typeof Set === 'function') { assert.ok(!_.isMap(new Set()), 'a set is not a map'); } if (typeof WeakSet === 'function') { assert.ok(!_.isMap(new WeakSet()), 'a weakset is not a map'); } if (typeof WeakMap === 'function') { assert.ok(!_.isMap(new WeakMap()), 'a weakmap is not a map'); } if (typeof Map === 'function') { var keyString = 'a string'; var obj = new Map(); obj.set(keyString, "value associated with 'a string'"); assert.ok(_.isMap(obj), 'but a map is'); } }); QUnit.test('isWeakMap', function(assert) { assert.ok(!_.isWeakMap('string'), 'a string is not a weakmap'); assert.ok(!_.isWeakMap(2), 'a number is not a weakmap'); assert.ok(!_.isWeakMap({}), 'an object is not a weakmap'); assert.ok(!_.isWeakMap(false), 'a boolean is not a weakmap'); assert.ok(!_.isWeakMap(void 0), 'undefined is not a weakmap'); assert.ok(!_.isWeakMap([1, 2, 3]), 'an array is not a weakmap'); if (typeof Set === 'function') { assert.ok(!_.isWeakMap(new Set()), 'a set is not a weakmap'); } if (typeof WeakSet === 'function') { assert.ok(!_.isWeakMap(new WeakSet()), 'a weakset is not a weakmap'); } if (typeof Map === 'function') { assert.ok(!_.isWeakMap(new Map()), 'a map is not a weakmap'); } if (typeof WeakMap === 'function') { var keyObj = {}, obj = new WeakMap(); obj.set(keyObj, 'value'); assert.ok(_.isWeakMap(obj), 'but a weakmap is'); } }); QUnit.test('isSet', function(assert) { assert.ok(!_.isSet('string'), 'a string is not a set'); assert.ok(!_.isSet(2), 'a number is not a set'); assert.ok(!_.isSet({}), 'an object is not a set'); assert.ok(!_.isSet(false), 'a boolean is not a set'); assert.ok(!_.isSet(void 0), 'undefined is not a set'); assert.ok(!_.isSet([1, 2, 3]), 'an array is not a set'); if (typeof Map === 'function') { assert.ok(!_.isSet(new Map()), 'a map is not a set'); } if (typeof WeakMap === 'function') { assert.ok(!_.isSet(new WeakMap()), 'a weakmap is not a set'); } if (typeof WeakSet === 'function') { assert.ok(!_.isSet(new WeakSet()), 'a weakset is not a set'); } if (typeof Set === 'function') { var obj = new Set([1, 2, 3, 4, 5]); assert.ok(_.isSet(obj), 'but a set is'); } }); QUnit.test('isWeakSet', function(assert) { assert.ok(!_.isWeakSet('string'), 'a string is not a weakset'); assert.ok(!_.isWeakSet(2), 'a number is not a weakset'); assert.ok(!_.isWeakSet({}), 'an object is not a weakset'); assert.ok(!_.isWeakSet(false), 'a boolean is not a weakset'); assert.ok(!_.isWeakSet(void 0), 'undefined is not a weakset'); assert.ok(!_.isWeakSet([1, 2, 3]), 'an array is not a weakset'); if (typeof Map === 'function') { assert.ok(!_.isWeakSet(new Map()), 'a map is not a weakset'); } if (typeof WeakMap === 'function') { assert.ok(!_.isWeakSet(new WeakMap()), 'a weakmap is not a weakset'); } if (typeof Set === 'function') { assert.ok(!_.isWeakSet(new Set()), 'a set is not a weakset'); } if (typeof WeakSet === 'function') { var obj = new WeakSet(); obj.add({x: 1}, {y: 'string'}).add({y: 'string'}).add({z: [1, 2, 3]}); assert.ok(_.isWeakSet(obj), 'but a weakset is'); } }); QUnit.test('isFunction', function(assert) { assert.ok(!_.isFunction(void 0), 'undefined vars are not functions'); assert.ok(!_.isFunction([1, 2, 3]), 'arrays are not functions'); assert.ok(!_.isFunction('moe'), 'strings are not functions'); assert.ok(_.isFunction(_.isFunction), 'but functions are'); assert.ok(_.isFunction(function(){}), 'even anonymous ones'); if (testElement) { assert.ok(!_.isFunction(testElement), 'elements are not functions'); } var nodelist = typeof document != 'undefined' && document.childNodes; if (nodelist) { assert.ok(!_.isFunction(nodelist)); } }); if (typeof Int8Array !== 'undefined') { QUnit.test('#1929 Typed Array constructors are functions', function(assert) { _.chain(['Float32Array', 'Float64Array', 'Int8Array', 'Int16Array', 'Int32Array', 'Uint8Array', 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array']) .map(_.propertyOf(typeof global != 'undefined' ? global : window)) .compact() .each(function(TypedArray) { // PhantomJS reports `typeof UInt8Array == 'object'` and doesn't report toString TypeArray // as a function assert.strictEqual(_.isFunction(TypedArray), Object.prototype.toString.call(TypedArray) === '[object Function]'); }); }); } QUnit.test('isDate', function(assert) { assert.ok(!_.isDate(100), 'numbers are not dates'); assert.ok(!_.isDate({}), 'objects are not dates'); assert.ok(_.isDate(new Date()), 'but dates are'); }); QUnit.test('isRegExp', function(assert) { assert.ok(!_.isRegExp(_.identity), 'functions are not RegExps'); assert.ok(_.isRegExp(/identity/), 'but RegExps are'); }); QUnit.test('isFinite', function(assert) { assert.ok(!_.isFinite(void 0), 'undefined is not finite'); assert.ok(!_.isFinite(null), 'null is not finite'); assert.ok(!_.isFinite(NaN), 'NaN is not finite'); assert.ok(!_.isFinite(Infinity), 'Infinity is not finite'); assert.ok(!_.isFinite(-Infinity), '-Infinity is not finite'); assert.ok(_.isFinite('12'), 'Numeric strings are numbers'); assert.ok(!_.isFinite('1a'), 'Non numeric strings are not numbers'); assert.ok(!_.isFinite(''), 'Empty strings are not numbers'); var obj = new Number(5); assert.ok(_.isFinite(obj), 'Number instances can be finite'); assert.ok(_.isFinite(0), '0 is finite'); assert.ok(_.isFinite(123), 'Ints are finite'); assert.ok(_.isFinite(-12.44), 'Floats are finite'); if (typeof Symbol === 'function') { assert.ok(!_.isFinite(Symbol()), 'symbols are not numbers'); assert.ok(!_.isFinite(Symbol('description')), 'described symbols are not numbers'); assert.ok(!_.isFinite(Object(Symbol())), 'boxed symbols are not numbers'); } }); QUnit.test('isNaN', function(assert) { assert.ok(!_.isNaN(void 0), 'undefined is not NaN'); assert.ok(!_.isNaN(null), 'null is not NaN'); assert.ok(!_.isNaN(0), '0 is not NaN'); assert.ok(!_.isNaN(new Number(0)), 'wrapped 0 is not NaN'); assert.ok(_.isNaN(NaN), 'but NaN is'); assert.ok(_.isNaN(new Number(NaN)), 'wrapped NaN is still NaN'); if (typeof Symbol !== 'undefined'){ assert.ok(!_.isNaN(Symbol()), 'symbol is not NaN'); } }); QUnit.test('isNull', function(assert) { assert.ok(!_.isNull(void 0), 'undefined is not null'); assert.ok(!_.isNull(NaN), 'NaN is not null'); assert.ok(_.isNull(null), 'but null is'); }); QUnit.test('isUndefined', function(assert) { assert.ok(!_.isUndefined(1), 'numbers are defined'); assert.ok(!_.isUndefined(null), 'null is defined'); assert.ok(!_.isUndefined(false), 'false is defined'); assert.ok(!_.isUndefined(NaN), 'NaN is defined'); assert.ok(_.isUndefined(), 'nothing is undefined'); assert.ok(_.isUndefined(void 0), 'undefined is undefined'); }); QUnit.test('isError', function(assert) { assert.ok(!_.isError(1), 'numbers are not Errors'); assert.ok(!_.isError(null), 'null is not an Error'); assert.ok(!_.isError(Error), 'functions are not Errors'); assert.ok(_.isError(new Error()), 'Errors are Errors'); assert.ok(_.isError(new EvalError()), 'EvalErrors are Errors'); assert.ok(_.isError(new RangeError()), 'RangeErrors are Errors'); assert.ok(_.isError(new ReferenceError()), 'ReferenceErrors are Errors'); assert.ok(_.isError(new SyntaxError()), 'SyntaxErrors are Errors'); assert.ok(_.isError(new TypeError()), 'TypeErrors are Errors'); assert.ok(_.isError(new URIError()), 'URIErrors are Errors'); }); if (typeof ArrayBuffer != 'undefined') { QUnit.test('isArrayBuffer, isDataView and isTypedArray', function(assert) { var buffer = new ArrayBuffer(16); var checkValues = { 'null': null, 'a string': '', 'an array': [], 'an ArrayBuffer': buffer, 'a TypedArray': new Uint8Array(buffer) }; // Some older browsers support typed arrays but not DataView. if (DataViewImpl) { checkValues['a DataView'] = new DataViewImpl(buffer); } var types = ['an ArrayBuffer', 'a DataView', 'a TypedArray']; _.each(types, function(type) { var typeCheck = _['is' + type.split(' ')[1]]; _.each(checkValues, function(value, description) { if (description === type) { assert.ok(typeCheck(value), description + ' is ' + type); } else { assert.ok(!typeCheck(value), description + ' is not ' + type); } }); }); }); QUnit.test('isTypedArray', function(assert) { var buffer = new ArrayBuffer(16); var typedArrayTypes = [Int8Array, Uint16Array, Int16Array, Uint32Array, Int32Array, Float32Array, Float64Array]; if (typeof Uint8ClampedArray != 'undefined') { typedArrayTypes.push(Uint8ClampedArray); } if (typeof BigInt64Array != 'undefined') { typedArrayTypes.push(BigInt64Array); } _.each(typedArrayTypes, function(ctor) { assert.ok(_.isTypedArray(new ctor(buffer)), ctor.name + ' is a typed array'); }); }); } QUnit.test('tap', function(assert) { var intercepted = null; var interceptor = function(obj) { intercepted = obj; }; var returned = _.tap(1, interceptor); assert.strictEqual(intercepted, 1, 'passes tapped object to interceptor'); assert.strictEqual(returned, 1, 'returns tapped object'); returned = _([1, 2, 3]).chain(). map(function(n){ return n * 2; }). max(). tap(interceptor). value(); assert.strictEqual(returned, 6, 'can use tapped objects in a chain'); assert.strictEqual(intercepted, returned, 'can use tapped objects in a chain'); }); QUnit.test('has', function(assert) { var obj = {foo: 'bar', func: function(){}}; assert.ok(_.has(obj, 'foo'), 'checks that the object has a property.'); assert.ok(!_.has(obj, 'baz'), "returns false if the object doesn't have the property."); assert.ok(_.has(obj, 'func'), 'works for functions too.'); obj.hasOwnProperty = null; assert.ok(_.has(obj, 'foo'), 'works even when the hasOwnProperty method is deleted.'); function Child() {} Child.prototype = obj; var child = new Child(); assert.ok(!_.has(child, 'foo'), 'does not check the prototype chain for a property.'); assert.strictEqual(_.has(null, 'foo'), false, 'returns false for null'); assert.strictEqual(_.has(void 0, 'foo'), false, 'returns false for undefined'); assert.ok(_.has({a: {b: 'foo'}}, ['a', 'b']), 'can check for nested properties.'); assert.ok(!_.has({a: child}, ['a', 'foo']), 'does not check the prototype of nested props.'); }); QUnit.test('get', function(assert) { var stooge = {name: 'moe'}; assert.strictEqual(_.get(stooge, 'name'), 'moe', 'should return the property with the given name'); assert.strictEqual(_.get(null, 'name'), void 0, 'should return undefined for null values'); assert.strictEqual(_.get(void 0, 'name'), void 0, 'should return undefined for undefined values'); assert.strictEqual(_.get('foo', null), void 0, 'should return undefined for null object'); assert.strictEqual(_.get({x: null}, 'x'), null, 'can fetch null values'); assert.strictEqual(_.get(null, 'length'), void 0, 'does not crash on property access of non-objects'); assert.strictEqual(_.get(stooge, 'size', 10), 10, 'allows a fallback value for undefined properties'); assert.strictEqual(_.get(stooge, 'name', 10), 'moe', 'ignores the fallback value if the property is defined'); // Deep property access assert.strictEqual(_.get({a: 1}, 'a'), 1, 'can get a direct property'); assert.strictEqual(_.get({a: {b: 2}}, ['a', 'b']), 2, 'can get a nested property'); assert.strictEqual(_.get({a: {b: 2}}, ['a', 'c'], 10), 10, 'allows a fallback value for undefined properties'); assert.strictEqual(_.get({a: {b: 2}}, ['a', 'b'], 10), 2, 'ignores the fallback value if the property is defined'); assert.strictEqual(_.get({a: false}, ['a']), false, 'can fetch falsy values'); assert.strictEqual(_.get({x: {y: null}}, ['x', 'y']), null, 'can fetch null values deeply'); assert.strictEqual(_.get({x: null}, ['x', 'y']), void 0, 'does not crash on property access of nested non-objects'); assert.strictEqual(_.get({x: 'y'}, []), void 0, 'returns `undefined` for a path that is an empty array'); }); QUnit.test('property', function(assert) { var stooge = {name: 'moe'}; assert.strictEqual(_.property('name')(stooge), 'moe', 'should return the property with the given name'); assert.strictEqual(_.property('name')(null), void 0, 'should return undefined for null values'); assert.strictEqual(_.property('name')(void 0), void 0, 'should return undefined for undefined values'); assert.strictEqual(_.property(null)('foo'), void 0, 'should return undefined for null object'); assert.strictEqual(_.property('x')({x: null}), null, 'can fetch null values'); assert.strictEqual(_.property('length')(null), void 0, 'does not crash on property access of non-objects'); // Deep property access assert.strictEqual(_.property('a')({a: 1}), 1, 'can get a direct property'); assert.strictEqual(_.property(['a', 'b'])({a: {b: 2}}), 2, 'can get a nested property'); assert.strictEqual(_.property(['a'])({a: false}), false, 'can fetch falsy values'); assert.strictEqual(_.property(['x', 'y'])({x: {y: null}}), null, 'can fetch null values deeply'); assert.strictEqual(_.property(['x', 'y'])({x: null}), void 0, 'does not crash on property access of nested non-objects'); assert.strictEqual(_.property([])({x: 'y'}), void 0, 'returns `undefined` for a path that is an empty array'); }); QUnit.test('propertyOf', function(assert) { var stoogeRanks = _.propertyOf({curly: 2, moe: 1, larry: 3}); assert.strictEqual(stoogeRanks('curly'), 2, 'should return the property with the given name'); assert.strictEqual(stoogeRanks(null), void 0, 'should return undefined for null values'); assert.strictEqual(stoogeRanks(void 0), void 0, 'should return undefined for undefined values'); assert.strictEqual(_.propertyOf({a: null})('a'), null, 'can fetch null values'); function MoreStooges() { this.shemp = 87; } MoreStooges.prototype = {curly: 2, moe: 1, larry: 3}; var moreStoogeRanks = _.propertyOf(new MoreStooges()); assert.strictEqual(moreStoogeRanks('curly'), 2, 'should return properties from further up the prototype chain'); var nullPropertyOf = _.propertyOf(null); assert.strictEqual(nullPropertyOf('curly'), void 0, 'should return undefined when obj is null'); var undefPropertyOf = _.propertyOf(void 0); assert.strictEqual(undefPropertyOf('curly'), void 0, 'should return undefined when obj is undefined'); var deepPropertyOf = _.propertyOf({curly: {number: 2}, joe: {number: null}}); assert.strictEqual(deepPropertyOf(['curly', 'number']), 2, 'can fetch nested properties of obj'); assert.strictEqual(deepPropertyOf(['joe', 'number']), null, 'can fetch nested null properties of obj'); }); QUnit.test('isMatch', function(assert) { var moe = {name: 'Moe Howard', hair: true}; var curly = {name: 'Curly Howard', hair: false}; assert.strictEqual(_.isMatch(moe, {hair: true}), true, 'Returns a boolean'); assert.strictEqual(_.isMatch(curly, {hair: true}), false, 'Returns a boolean'); assert.strictEqual(_.isMatch(5, {__x__: void 0}), false, 'can match undefined props on primitives'); assert.strictEqual(_.isMatch({__x__: void 0}, {__x__: void 0}), true, 'can match undefined props'); assert.strictEqual(_.isMatch(null, {}), true, 'Empty spec called with null object returns true'); assert.strictEqual(_.isMatch(null, {a: 1}), false, 'Non-empty spec called with null object returns false'); _.each([null, void 0], function(item) { assert.strictEqual(_.isMatch(item, null), true, 'null matches null'); }); _.each([null, void 0], function(item) { assert.strictEqual(_.isMatch(item, null), true, 'null matches {}'); }); assert.strictEqual(_.isMatch({b: 1}, {a: void 0}), false, 'handles undefined values (1683)'); _.each([true, 5, NaN, null, void 0], function(item) { assert.strictEqual(_.isMatch({a: 1}, item), true, 'treats primitives as empty'); }); function Prototest() {} Prototest.prototype.x = 1; var specObj = new Prototest; assert.strictEqual(_.isMatch({x: 2}, specObj), true, 'spec is restricted to own properties'); specObj.y = 5; assert.strictEqual(_.isMatch({x: 1, y: 5}, specObj), true); assert.strictEqual(_.isMatch({x: 1, y: 4}, specObj), false); assert.ok(_.isMatch(specObj, {x: 1, y: 5}), 'inherited and own properties are checked on the test object'); Prototest.x = 5; assert.ok(_.isMatch({x: 5, y: 1}, Prototest), 'spec can be a function'); //null edge cases var oCon = {constructor: Object}; assert.deepEqual(_.map([null, void 0, 5, {}], _.partial(_.isMatch, _, oCon)), [false, false, false, true], 'doesnt falsy match constructor on undefined/null'); }); QUnit.test('matcher', function(assert) { var moe = {name: 'Moe Howard', hair: true}; var curly = {name: 'Curly Howard', hair: false}; var stooges = [moe, curly]; assert.strictEqual(_.matcher({hair: true})(moe), true, 'Returns a boolean'); assert.strictEqual(_.matcher({hair: true})(curly), false, 'Returns a boolean'); assert.strictEqual(_.matcher({__x__: void 0})(5), false, 'can match undefined props on primitives'); assert.strictEqual(_.matcher({__x__: void 0})({__x__: void 0}), true, 'can match undefined props'); assert.strictEqual(_.matcher({})(null), true, 'Empty spec called with null object returns true'); assert.strictEqual(_.matcher({a: 1})(null), false, 'Non-empty spec called with null object returns false'); assert.strictEqual(_.find(stooges, _.matcher({hair: false})), curly, 'returns a predicate that can be used by finding functions.'); assert.strictEqual(_.find(stooges, _.matcher(moe)), moe, 'can be used to locate an object exists in a collection.'); assert.deepEqual(_.filter([null, void 0], _.matcher({a: 1})), [], 'Do not throw on null values.'); assert.deepEqual(_.filter([null, void 0], _.matcher(null)), [null, void 0], 'null matches null'); assert.deepEqual(_.filter([null, void 0], _.matcher({})), [null, void 0], 'null matches {}'); assert.deepEqual(_.filter([{b: 1}], _.matcher({a: void 0})), [], 'handles undefined values (1683)'); _.each([true, 5, NaN, null, void 0], function(item) { assert.strictEqual(_.matcher(item)({a: 1}), true, 'treats primitives as empty'); }); function Prototest() {} Prototest.prototype.x = 1; var specObj = new Prototest; var protospec = _.matcher(specObj); assert.strictEqual(protospec({x: 2}), true, 'spec is restricted to own properties'); specObj.y = 5; protospec = _.matcher(specObj); assert.strictEqual(protospec({x: 1, y: 5}), true); assert.strictEqual(protospec({x: 1, y: 4}), false); assert.ok(_.matcher({x: 1, y: 5})(specObj), 'inherited and own properties are checked on the test object'); Prototest.x = 5; assert.ok(_.matcher(Prototest)({x: 5, y: 1}), 'spec can be a function'); // #1729 var o = {b: 1}; var m = _.matcher(o); assert.strictEqual(m({b: 1}), true); o.b = 2; o.a = 1; assert.strictEqual(m({b: 1}), true, 'changing spec object doesnt change matches result'); //null edge cases var oCon = _.matcher({constructor: Object}); assert.deepEqual(_.map([null, void 0, 5, {}], oCon), [false, false, false, true], 'doesnt falsy match constructor on undefined/null'); }); QUnit.test('matches', function(assert) { assert.strictEqual(_.matches, _.matcher, 'is an alias for matcher'); }); QUnit.test('findKey', function(assert) { var objects = { a: {a: 0, b: 0}, b: {a: 1, b: 1}, c: {a: 2, b: 2} }; assert.strictEqual(_.findKey(objects, function(obj) { return obj.a === 0; }), 'a'); assert.strictEqual(_.findKey(objects, function(obj) { return obj.b * obj.a === 4; }), 'c'); assert.strictEqual(_.findKey(objects, 'a'), 'b', 'Uses lookupIterator'); assert.strictEqual(_.findKey(objects, function(obj) { return obj.b * obj.a === 5; }), void 0); assert.strictEqual(_.findKey([1, 2, 3, 4, 5, 6], function(obj) { return obj === 3; }), '2', 'Keys are strings'); assert.strictEqual(_.findKey(objects, function(a) { return a.foo === null; }), void 0); _.findKey({a: {a: 1}}, function(a, key, obj) { assert.strictEqual(key, 'a'); assert.deepEqual(obj, {a: {a: 1}}); assert.strictEqual(this, objects, 'called with context'); }, objects); var array = [1, 2, 3, 4]; array.match = 55; assert.strictEqual(_.findKey(array, function(x) { return x === 55; }), 'match', 'matches array-likes keys'); }); QUnit.test('mapObject', function(assert) { var obj = {a: 1, b: 2}; var objects = { a: {a: 0, b: 0}, b: {a: 1, b: 1}, c: {a: 2, b: 2} }; assert.deepEqual(_.mapObject(obj, function(val) { return val * 2; }), {a: 2, b: 4}, 'simple objects'); assert.deepEqual(_.mapObject(objects, function(val) { return _.reduce(val, function(memo, v){ return memo + v; }, 0); }), {a: 0, b: 2, c: 4}, 'nested objects'); assert.deepEqual(_.mapObject(obj, function(val, key, o) { return o[key] * 2; }), {a: 2, b: 4}, 'correct keys'); assert.deepEqual(_.mapObject([1, 2], function(val) { return val * 2; }), {0: 2, 1: 4}, 'check behavior for arrays'); assert.deepEqual(_.mapObject(obj, function(val) { return val * this.multiplier; }, {multiplier: 3}), {a: 3, b: 6}, 'keep context'); assert.deepEqual(_.mapObject({a: 1}, function() { return this.length; }, [1, 2]), {a: 2}, 'called with context'); var ids = _.mapObject({length: 2, 0: {id: '1'}, 1: {id: '2'}}, function(n){ return n.id; }); assert.deepEqual(ids, {length: void 0, 0: '1', 1: '2'}, 'Check with array-like objects'); // Passing a property name like _.pluck. var people = {a: {name: 'moe', age: 30}, b: {name: 'curly', age: 50}}; assert.deepEqual(_.mapObject(people, 'name'), {a: 'moe', b: 'curly'}, 'predicate string map to object properties'); _.each([null, void 0, 1, 'abc', [], {}, void 0], function(val){ assert.deepEqual(_.mapObject(val, _.identity), {}, 'mapValue identity'); }); var Proto = function(){ this.a = 1; }; Proto.prototype.b = 1; var protoObj = new Proto(); assert.deepEqual(_.mapObject(protoObj, _.identity), {a: 1}, 'ignore inherited values from prototypes'); }); }()); ================================================ FILE: test/overrides.js ================================================ (function() { function overrideDataView() { NativeDataView = DataView; DataView = {}; } // Only override browser functions roughly 1/3rd of the time var runOverrides = Math.floor(Math.random() * 3) === 0; if (runOverrides) { overrideDataView(); } })(); ================================================ FILE: test/qunit-setup.js ================================================ (function() { QUnit.config.noglobals = true; }()); ================================================ FILE: test/treeshake.js ================================================ (function() { // Tests in this module only work in the node.js environment. if (typeof require !== 'function') return; var fixturePrefix = __dirname + '/../test-treeshake/'; var moduleName = __dirname + '/../underscore-umd.js'; var fs = require('fs'); QUnit.module('Tree-shaking'); QUnit.test('should have an effect', function(assert) { var done = assert.async(); var fixtureName = fixturePrefix + 'map-umd.js'; fs.stat(moduleName, function(error, moduleStats) { assert.equal(error, null); if (error) return done(); fs.stat(fixtureName, function(error, fixtureStats) { assert.equal(error, null); if (error) return done(); // _.template depends on the entire underscore object, so all of the // source code should be included. assert.ok(fixtureStats.size < moduleStats.size); done(); }); }); }); QUnit.test('should not be overzealous', function(assert) { var done = assert.async(); var fixtureName = fixturePrefix + 'template-umd.js'; fs.readFile(moduleName, {encoding: 'utf8'}, function(error, moduleData) { assert.equal(error, null); if (error) return done(); fs.readFile(fixtureName, {encoding: 'utf8'}, function(error, fixtureData) { assert.equal(error, null); if (error) return done(); var moduleLines = moduleData.split('\n').length, fixtureLines = fixtureData.split('\n').length; // _.template depends on the entire underscore object, so all of the // source code should be included. Allowing for up to 9 lines of // difference; this is the size of the noConflict logic plus the // copyright intro, both of which are present in the official module but // not in the fixture. assert.ok(moduleLines - fixtureLines <= 9); done(); }); }); }); }()); ================================================ FILE: test/utility.js ================================================ (function() { var _ = typeof require == 'function' ? require('..') : window._; var templateSettings; QUnit.module('Utility', { beforeEach: function() { templateSettings = _.clone(_.templateSettings); }, afterEach: function() { _.templateSettings = templateSettings; } }); if (typeof require != 'function') { QUnit.test('noConflict (browser)', function(assert) { var underscore = _.noConflict(); assert.strictEqual(underscore.identity(1), 1); if (typeof require != 'function') { assert.strictEqual(this._, void 0, 'global underscore is removed'); this._ = underscore; } else if (typeof global !== 'undefined') { delete global._; } }); } if (typeof require == 'function') { QUnit.test('noConflict (node vm)', function(assert) { assert.expect(2); var done = assert.async(); var fs = require('fs'); var vm = require('vm'); var filename = __dirname + '/../underscore-umd.js'; fs.readFile(filename, function(err, content){ var sandbox = vm.createScript( content + 'this.underscore = this._.noConflict();', filename ); var context = {_: 'oldvalue'}; sandbox.runInNewContext(context); assert.strictEqual(context._, 'oldvalue'); assert.strictEqual(context.underscore.VERSION, _.VERSION); done(); }); }); } if (typeof require == 'function') { QUnit.test('Legacy Node API', function(assert) { var filename = __dirname + '/../underscore-umd.js'; var resolved = require(filename); assert.strictEqual(resolved, resolved._); }); } QUnit.test('#750 - Return _ instance.', function(assert) { assert.expect(2); var instance = _([]); assert.strictEqual(_(instance), instance); assert.strictEqual(new _(instance), instance); }); QUnit.test('identity', function(assert) { var stooge = {name: 'moe'}; assert.strictEqual(_.identity(stooge), stooge, 'stooge is the same as his identity'); }); QUnit.test('constant', function(assert) { var stooge = {name: 'moe'}; assert.strictEqual(_.constant(stooge)(), stooge, 'should create a function that returns stooge'); }); QUnit.test('noop', function(assert) { assert.strictEqual(_.noop('curly', 'larry', 'moe'), void 0, 'should always return undefined'); }); QUnit.test('toPath', function(assert) { var key = 'xyz'; var path = [key]; assert.deepEqual(_.toPath(key), path, 'bare strings are wrapped in a single-element array'); assert.strictEqual(_.toPath(path), path, 'arrays are returned untouched'); }) QUnit.test('random', function(assert) { var array = _.range(1000); var min = Math.pow(2, 31); var max = Math.pow(2, 62); assert.ok(_.every(array, function() { return _.random(min, max) >= min; }), 'should produce a random number greater than or equal to the minimum number'); assert.ok(_.some(array, function() { return _.random(Number.MAX_VALUE) > 0; }), 'should produce a random number when passed `Number.MAX_VALUE`'); }); QUnit.test('now', function(assert) { var diff = _.now() - new Date().getTime(); assert.ok(diff <= 0 && diff > -5, 'Produces the correct time in milliseconds');//within 5ms }); QUnit.test('uniqueId', function(assert) { var ids = [], i = 0; while (i++ < 100) ids.push(_.uniqueId()); assert.strictEqual(_.uniq(ids).length, ids.length, 'can generate a globally-unique stream of ids'); }); QUnit.test('times', function(assert) { var vals = []; _.times(3, function(i) { vals.push(i); }); assert.deepEqual(vals, [0, 1, 2], 'is 0 indexed'); // vals = []; _(3).times(function(i) { vals.push(i); }); assert.deepEqual(vals, [0, 1, 2], 'works as a wrapper'); // collects return values assert.deepEqual([0, 1, 2], _.times(3, function(i) { return i; }), 'collects return values'); assert.deepEqual(_.times(0, _.identity), []); assert.deepEqual(_.times(-1, _.identity), []); assert.deepEqual(_.times(parseFloat('-Infinity'), _.identity), []); }); QUnit.test('mixin', function(assert) { var ret = _.mixin({ myReverse: function(string) { return string.split('').reverse().join(''); } }); assert.strictEqual(ret, _, 'returns the _ object to facilitate chaining'); assert.strictEqual(_.myReverse('panacea'), 'aecanap', 'mixed in a function to _'); assert.strictEqual(_('champ').myReverse(), 'pmahc', 'mixed in a function to the OOP wrapper'); }); QUnit.test('_.escape', function(assert) { assert.strictEqual(_.escape(null), ''); }); QUnit.test('_.unescape', function(assert) { var string = 'Curly & Moe'; assert.strictEqual(_.unescape(null), ''); assert.strictEqual(_.unescape(_.escape(string)), string); assert.strictEqual(_.unescape(string), string, 'don\'t unescape unnecessarily'); }); // Don't care what they escape them to just that they're escaped and can be unescaped QUnit.test('_.escape & unescape', function(assert) { // test & (&) separately obviously var escapeCharacters = ['<', '>', '"', '\'', '`']; _.each(escapeCharacters, function(escapeChar) { var s = 'a ' + escapeChar + ' string escaped'; var e = _.escape(s); assert.notEqual(s, e, escapeChar + ' is escaped'); assert.strictEqual(s, _.unescape(e), escapeChar + ' can be unescaped'); s = 'a ' + escapeChar + escapeChar + escapeChar + 'some more string' + escapeChar; e = _.escape(s); assert.strictEqual(e.indexOf(escapeChar), -1, 'can escape multiple occurrences of ' + escapeChar); assert.strictEqual(_.unescape(e), s, 'multiple occurrences of ' + escapeChar + ' can be unescaped'); }); // handles multiple escape characters at once var joiner = ' other stuff '; var allUnescaped = escapeCharacters.join(joiner); allUnescaped += allUnescaped; var allEscaped = _.escape(allUnescaped); assert.ok(_.every(escapeCharacters), function(escapeChar) { return allEscaped.indexOf(escapeChar) === -1; }, 'replaces all occurrences'); assert.strictEqual(_.unescape(allEscaped), allUnescaped, 'undos all replacements'); // test & -> & var str = 'some string & another string & yet another'; var escaped = _.escape(str); assert.notStrictEqual(escaped.indexOf('&'), -1, 'handles & aka &'); assert.strictEqual(_.unescape(str), str, 'can unescape &'); }); QUnit.test('template', function(assert) { var basicTemplate = _.template("<%= thing %> is gettin' on my noives!"); var result = basicTemplate({thing: 'This'}); assert.strictEqual(result, "This is gettin' on my noives!", 'can do basic attribute interpolation'); var sansSemicolonTemplate = _.template('A <% this %> B'); assert.strictEqual(sansSemicolonTemplate(), 'A B'); var backslashTemplate = _.template('<%= thing %> is \\ridanculous'); assert.strictEqual(backslashTemplate({thing: 'This'}), 'This is \\ridanculous'); var escapeTemplate = _.template('<%= a ? "checked=\\"checked\\"" : "" %>'); assert.strictEqual(escapeTemplate({a: true}), 'checked="checked"', 'can handle slash escapes in interpolations.'); var fancyTemplate = _.template(''); result = fancyTemplate({people: {moe: 'Moe', larry: 'Larry', curly: 'Curly'}}); assert.strictEqual(result, '', 'can run arbitrary javascript in templates'); var escapedCharsInJavaScriptTemplate = _.template(''); result = escapedCharsInJavaScriptTemplate({numbers: 'one\ntwo\nthree\nfour'}); assert.strictEqual(result, '', 'Can use escaped characters (e.g. \\n) in JavaScript'); var namespaceCollisionTemplate = _.template('<%= pageCount %> <%= thumbnails[pageCount] %> <% _.each(thumbnails, function(p) { %>
<% }); %>'); result = namespaceCollisionTemplate({ pageCount: 3, thumbnails: { 1: 'p1-thumbnail.gif', 2: 'p2-thumbnail.gif', 3: 'p3-thumbnail.gif' } }); assert.strictEqual(result, '3 p3-thumbnail.gif
'); var noInterpolateTemplate = _.template('

Just some text. Hey, I know this is silly but it aids consistency.

'); result = noInterpolateTemplate(); assert.strictEqual(result, '

Just some text. Hey, I know this is silly but it aids consistency.

'); var quoteTemplate = _.template("It's its, not it's"); assert.strictEqual(quoteTemplate({}), "It's its, not it's"); var quoteInStatementAndBody = _.template('<% ' + " if(foo == 'bar'){ " + "%>Statement quotes and 'quotes'.<% } %>"); assert.strictEqual(quoteInStatementAndBody({foo: 'bar'}), "Statement quotes and 'quotes'."); var withNewlinesAndTabs = _.template('This\n\t\tis: <%= x %>.\n\tok.\nend.'); assert.strictEqual(withNewlinesAndTabs({x: 'that'}), 'This\n\t\tis: that.\n\tok.\nend.'); var template = _.template('<%- value %>'); result = template({value: '